After successfully launching activity on physical device, application stops instatnly. NetworkOnMainThreadException - java

This is my entire code from an android project
Translator.java:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Translator extends AppCompatActivity {
EditText input;
TextView translated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate (View view) throws IOException {
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
String langFrom = "en";
String langTo = "hi";
// INSERT YOU URL HERE
String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String output = response.toString();
translated.setText(output);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
android:background="#FAF3BD"
tools:context=".Translator">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tagLine"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.023" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="300dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.144"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.069">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="#string/input"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/translateButton"
android:layout_width="175dp"
android:layout_height="67dp"
android:background="#FF9800"
android:onClick="translate"
android:text="#string/translateButton"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.46" />
enter code here
<com.google.android.material.textfield.TextInputLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/translateButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.144"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout"
app:layout_constraintVertical_bias="0.558">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/target_language"
android:textSize="24sp" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:id="#+id/translatedText"
android:layout_width="305dp"
android:layout_height="215dp"
android:background="#FDDB73"
android:scrollY="500dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:scrollHorizontally="false"
android:shadowColor="#FFFFFF"
android:text="#string/translated"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/translateButton"
app:layout_constraintVertical_bias="0.751" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/translated_text"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/translatedText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/translateButton"
app:layout_constraintVertical_bias="0.731" />
<View
android:id="#+id/divider2"
android:layout_width="350dp"
android:layout_height="2dp"
android:layout_marginTop="83dp"
android:layout_marginBottom="12dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toTopOf="#+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/translateButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dhimanujjwal.anuvaad">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".Translator">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat:
Process: com.dhimanujjwal.anuvaad, PID: 14480
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6412)
at android.view.View$PerformClick.run(View.java:25341)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6977)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6412) 
at android.view.View$PerformClick.run(View.java:25341) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6977) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:299)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:237)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(Unknown Source:0)
at com.dhimanujjwal.anuvaad.Translator.translate(Translator.java:45)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:6412) 
at android.view.View$PerformClick.run(View.java:25341) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6977) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910) 

You are getting Caused by: android.os.NetworkOnMainThreadException. I think it says everything. To execute operations like this You have to do it on another thread. You can use JobIntentService.
In Your manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.teststackjava">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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>
<service
android:name=".ExampleJobIntentService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
public class MainActivity extends AppCompatActivity
{
EditText input;
TextView translated;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate(View view)
{
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
// setting observer to translated text
ExampleJobIntentService.translatedText.observe(this,
new Observer<String>()
{
#Override
public void onChanged(String s)
{
translated.setText(s); // change text
}
}
);
Intent serviceIntent = new Intent(this,
ExampleJobIntentService.class
);
serviceIntent.putExtra("inputExtra", text);
ExampleJobIntentService.enqueueWork(this, serviceIntent);
}
}
Then create class which extends JobIntentService:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.lifecycle.MutableLiveData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ExampleJobIntentService extends JobIntentService
{
private static final String TAG = "ExampleJobIntentService";
// This is data type which can be observed by another class
public static MutableLiveData<String> translatedText = new MutableLiveData<>(); // I made it public, better to use private and getter
static void enqueueWork(Context context, Intent work)
{
enqueueWork(context, ExampleJobIntentService.class, 123, work);
}
#Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "onCreate");
}
#Override
protected void onHandleWork(#NonNull Intent intent)
{
Log.d(TAG, "onHandleWork");
String input = intent.getStringExtra("inputExtra");
String langFrom = "en";
String langTo = "hi";
// INSERT YOU URL HERE
try
{
String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
"?q=" + URLEncoder.encode(input, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
String output = response.toString();
Log.i(TAG, "onHandleWork: " + output);
translatedText.postValue(output);//here I am updating data
}
catch (IOException e)
{
Log.i(TAG, "onHandleWork: ERROR");
}
}
#Override
public void onDestroy()
{
Log.d(TAG, "onDestroy");
super.onDestroy();
}
#Override
public boolean onStopCurrentWork()
{
Log.d(TAG, "onStopCurrentWork");
return super.onStopCurrentWork();
}
}
activity_main.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">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="input"
android:textSize="24sp" />
<Button
android:id="#+id/translateButton"
android:layout_width="175dp"
android:layout_height="67dp"
android:background="#FF9800"
android:onClick="translate"
android:text="translateButton"
android:textSize="30sp" />
<TextView
android:id="#+id/translatedText"
android:layout_width="305dp"
android:layout_height="215dp"
android:background="#FDDB73"
android:scrollY="500dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:scrollHorizontally="false"
android:shadowColor="#FFFFFF"
android:text="translated"
android:textSize="24sp" />
</LinearLayout>
I have tested this and it seems to work when I tried to translate School I got स्कूल.

I think you forgot to account for the Button in the Java file, you need to create and link the Button and then setOnClickListener() for it , to tell what happens when the Button Clicks.

Your method transform should must match signature of View.OnClickListener.
You need delete throws IOException it, and handle exception inside method with try/catch block

If you run your app in device with version Android 9 (API level 28) or later, cleartext support is disabled by default. Then your AndroidManifest.xml file should add the line:
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>

Related

Android App crashes on Button running thread pressed | Java

I am creating an app to check whether the given address of a server is valid or not. It sends request to a server when Connect button is pressed. If request succeed it is valid if not invalid ...
But I am having an error when I run a thread. I cant run it on Computer caz having issues enabling ADV but here is my code.
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Server Address"
app:layout_constraintBottom_toTopOf="#+id/addressInput"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.869" />
<EditText
android:id="#+id/addressInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:hint="Enter your server address"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/addressBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect"
android:onClick="onAddressButtonClick"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addressInput"
app:layout_constraintVertical_bias="0.065" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
package com.naveed.youtubestream;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button addressBtn;
private EditText addressInput;
private String serverAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressBtn = findViewById(R.id.addressBtn);
addressInput = findViewById(R.id.addressInput);
}
private boolean checkAddress(String address){
try {
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
return true;
}
} catch (IOException e) { }
return false;
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
try{
if(checkAddress(serverAddress)){
//TODO --> Set new Layout
Toast.makeText(getApplicationContext(), "Server address was valid.", Toast.LENGTH_LONG).show();
}
else {
addressInput.setText("");
Toast.makeText(getApplicationContext(), "Invalid server address.", Toast.LENGTH_LONG).show();
}
}
catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
public void onAddressButtonClick(View view) {
try{
serverAddress = addressInput.getText().toString();
Thread thread = new Thread(runnable);
thread.start();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.naveed.youtubestream">
<uses-permission android:name="android.permission.INTERNET"/>
<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>
</manifest>

Why does this Android program crash after calling save? [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 4 years ago.
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.adufordjour.external">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
<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>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.adufordjour.external.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="61dp"
android:text="NAME"
android:id="#+id/textView"
/>
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="32dp"
android:layout_marginTop="44dp"
android:layout_toEndOf="#+id/textView"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText"
android:layout_centerVertical="true"
android:text="Save"
android:onClick="sAVE"/>
</RelativeLayout>
Android code
This is the code for storing data on a public external device:
package com.example.adufordjour.external;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = findViewById(R.id.editText);
}
This is the method for saving to the public external device
public void sAVE(View view){
String st1 = editText1.getText().toString();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myFile");
FileOutputStream fileOutputStream=null;
try {
if (isExternalStorageWritable()==true){
fileOutputStream =new FileOutputStream(file);
fileOutputStream.write(st1.getBytes());}
else {
Toast.makeText(this, "not saved", Toast.LENGTH_SHORT).show();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "file save at" + " " + "myFile", Toast.LENGTH_SHORT).show();
}
public boolean isExternalStorageWritable(){
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
else {
return false;
}
}
}
Why do you use android:maxSdkVersion="18" in uses-permission? I think it's not needed there.
Try to add READ_EXTERNAL_STORAGE permission and check if it worked. If not, paste stack trace of your crash.

Android Studio: Code is done, but app is crashing everytime I try to run

I've made an app that allows user to login but everytime I try to run, my App is crashing constantly.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mertino11.ourapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".FireApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_account.xml (XML for user logged in succesfully)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_account"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mertino11.ourapplication.AccountActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Account Page"
android:ems="10"
android:id="#+id/editText"
android:textSize="22sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textStyle="normal|bold"
android:textAlignment="center" />
</RelativeLayout>
activity_main.xml (login page)
<?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"
android:baselineAligned="false">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailField"
android:hint="Email"
android:paddingTop="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/passwordField"
android:hint="Password"
android:fontFamily="sans-serif"
android:paddingTop="20dp" />
<Button
android:text="Login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/loginBtn"
android:paddingTop="20dp" />
</LinearLayout>
Java --> Class: AccountActivity (Page when the user logged in successfully)
package com.example.mertino11.ourapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class AccountActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
}
}
Java --> Class: FireApp (Firebase settings I think)
package com.example.mertino11.ourapplication;
import android.app.Application;
import com.firebase.client.Firebase;
/**
* Created by Mertino11 on 10-Dec-16.
*/
public class FireApp extends Application {
#Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
}
}
Java --> Class: Main Activity (Back-end logging with account)
package com.example.mertino11.ourapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(MainActivity.this, AccountActivity.class));
}
}
};
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSignIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startSignIn() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "Fields are empty!", Toast.LENGTH_LONG).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign In Problem!", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Error Message at Run:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mertino11.ourapplication, PID: 3060
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.mertino11.ourapplication.MainActivity$1.onAuthStateChanged(MainActivity.java:48)
at com.google.firebase.auth.FirebaseAuth$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
Screenshot of the error:
http://i66.tinypic.com/51btrp.png
The scenario of the app:
Create account firebase Google (manually)
Opens app --> Sees login page
Logs in with accountdetails of Firebase
Goes to AccountActivity page
Note: I am a amateur/beginner with AndroidStudio.
The error is pretty self-explanatory.
You have missed adding the AccounActivity on your manifest...
<application
android:name=".FireApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".AccountActivity"
android:theme="#style/AppTheme" />
</application>
Add AccountActivity in your AndroidManifest.xml
<activity
android:name=".AccountActivity">
<intent-filter>
...
</intent-filter>
</activity>
Always carefully read logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?
I thank you all for giving me the solution. However (If it is possible) do you guys know why my App is running AccountActivity first instead of my Mainactivity? (it should run the mainactivity first)?
add .AccountActivity in manifest file as
<activity
android:name=".AccountActivity">
</activity>

Login With Facebook Android App

I am trying to implement login with Facebook on my Android app. I am using the following tutorial http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837. I have no errors in the code but when I try to access the activity where the login with Facebook button is located I get a run time error. It cannot load the activity.
Logcat
04-06 14:57:05.024 8470-8470/com.example.martin.ivebeenthere E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.martin.ivebeenthere.Login.onCreate(Login.java:34)
at android.app.Activity.performCreate(Activity.java:5047)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
at android.app.ActivityThread.access$700(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Caused by: null
at com.facebook.internal.Validate.sdkInitialized(Validate.java:99)
at com.facebook.FacebookSdk.getCallbackRequestCodeOffset(FacebookSdk.java:735)
at com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode(CallbackManagerImpl.java:109)
at com.facebook.login.widget.LoginButton.<clinit>(LoginButton.java:58)
at java.lang.reflect.Constructor.constructNative(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 
at android.view.LayoutInflater.createView(LayoutInflater.java:587) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:736) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
at com.example.martin.ivebeenthere.Login.onCreate(Login.java:34) 
at android.app.Activity.performCreate(Activity.java:5047) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117) 
at android.app.ActivityThread.access$700(ActivityThread.java:134) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4867) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774) 
at dalvik.system.NativeStart.main(Native Method) 
Login.java
package com.example.martin.ivebeenthere;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.table.TableOperationCallback;
import java.net.MalformedURLException;
public class Login extends AppCompatActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_login);
info = (TextView)findViewById(R.id.info);
loginButton = (LoginButton)findViewById(R.id.login_button);
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 e) {
info.setText("Login attempt failed.");
}
});
}
public void onClickbtnFeed(View view)
{
startActivity(new Intent(Login.this, Feed.class));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.martin.ivebeenthere">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".Home"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="com.example.splash.CLEARSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:label="#string/title_activity_login"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Register"
android:label="#string/title_activity_register"
android:theme="#style/AppTheme.NoActionBar" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<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" />
<activity
android:name=".Map"
android:label="#string/title_activity_map" />
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Feed"
android:label="#string/title_activity_feed"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".CheckinInfo"
android:label="#string/title_activity_checkin_info"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Account"
android:label="#string/title_activity_account"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EditAccount"
android:label="#string/title_activity_edit_account"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Checkin"
android:label="#string/title_activity_checkin"
android:theme="#style/AppTheme.NoActionBar" />
</application>
</manifest>
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="com.example.martin.ivebeenthere.Login">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_login" />
</android.support.design.widget.CoordinatorLayout>
content_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.martin.ivebeenthere.Login"
tools:showIn="#layout/activity_login">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#drawable/logo"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="276dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="Username"
android:id="#+id/editText"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Password"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/button3"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:onClick="onClickbtnFeed"/>
<!--<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Login With Facebook"
android:id="#+id/button4"
android:background="#3b5998"
android:textColor="#ffffff"
android:layout_below="#+id/button3"
android:layout_alignLeft="#+id/button3"
android:layout_alignStart="#+id/button3"
android:layout_marginTop="25dp" />-->
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
<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"
/>
</RelativeLayout>
Update with below code.
activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="16sp" />
</LinearLayout>
Login.java
import java.util.Arrays;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class Login extends FragmentActivity {
private LoginButton loginBtn;
private TextView username;
private UiLifecycleHelper uiHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (TextView) findViewById(R.id.username);
loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setReadPermissions(Arrays.asList("email"));
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
username.setText("You are currently logged in as " + user.getName());
} else {
username.setText("You are not logged in.");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("Login", "Facebook session opened.");
} else if (state.isClosed()) {
Log.d("Login", "Facebook session closed.");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.martin.ivebeenthere"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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=".Login"
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="com.facebook.LoginActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/APP_ID" />
</application>
</manifest>

Cannot Redirect SignUp Button to Sign Up page since Unable to start activity ComponentInfo error occurs

I'm trying to implement a login Activity. In login Activity, I have to enter Mobile number and password and then click the Login button.
Here is my activity_login.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background2"
tools:context="com.myayubo.LoginActivity"
android:fillViewport="false">
<RelativeLayout
android:id="#+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="25dp">
<LinearLayout
android:id="#+id/LinearLayouttxtayubo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textAyubo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ayubo"
android:layout_gravity="center"
android:typeface="normal"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:textSize="35dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayouttxtexplorer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/LinearLayouttxtayubo"
android:orientation="vertical">
<TextView
android:id="#+id/textExplore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explore places nearby you"
android:layout_centerHorizontal="true"
android:typeface="serif"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:textSize="12dp"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginTop="224dp"
android:layout_below="#+id/RelativeLayout1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<EditText
android:id="#+id/mobileNo"
android:layout_width="250dp"
android:layout_height="30dp"
android:hint="Mobile Number"
android:textColorHint="#FFFFFF"
android:gravity="center"
android:inputType="phone"
android:layout_gravity="center"
android:background="#drawable/shape"
android:layout_marginTop="10dp"
android:textSize="15dp"
>
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="250dp"
android:layout_height="30dp"
android:hint="Password"
android:textColorHint="#FFFFFF"
android:inputType="textPassword"
android:layout_gravity="center"
android:background="#drawable/shape"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="15dp"/>
<Button
android:id="#+id/loginBtn"
android:text="Login"
android:layout_width="260dp"
android:layout_height="38dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:alpha="0.5" />
<Button
android:id="#+id/fbbtn"
android:text="Connect with Facebook"
android:layout_width="250dp"
android:layout_height="26dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#ADD8E6"
android:alpha="0.5"
/>
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/fbbtn"
android:layout_marginTop="20dp"
android:text="or Sign Up"
android:layout_gravity="center"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
And Here is my LoginActivity.java
package com.myayubo;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.myayubo.services.MessageHandler;
import com.myayubo.services.ServiceHandler;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity implements View.OnClickListener {
public final static String URL = "";
public static String Uid;
private EditText contact;
private EditText password;
private Button login;
private Button fbBtn;
private TextView signUp;
private boolean errorStatus;
private ServiceHandler sh = new ServiceHandler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
contact = (EditText) findViewById(R.id.mobileNo);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.loginBtn);
fbBtn = (Button) findViewById(R.id.fbbtn);
signUp = (TextView) findViewById(R.id.signUp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!ServiceHandler.isOnline(getApplicationContext())){
MessageHandler.showMessage("No network connection",
getApplicationContext());
}
new Thread(new Runnable() {
public void run() {
Looper.prepare();
String mobile = contact.getText().toString();
String passwrd = password.getText().toString();
if (mobile.length() == 0){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Contact Number",
getApplicationContext());
errorStatus = true;
}
});
;
}
if (passwrd.length() == 0){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Password",
getApplicationContext());
errorStatus = true;
}
});
;
}
String jsonStr = null;
if (!errorStatus) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("No network connection",
getApplicationContext());
} else {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// notify user you are online
try{
runOnUiThread(new Runnable() {
public void run() {
}
});
;
jsonStr = sh.makeServiceCall(URL + "/" + mobile + "/"
+ passwrd, ServiceHandler.GET);
System.out.println(URL + "/" + mobile + "/"
+ passwrd);
}
catch (Exception e){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage("No network connection",
getApplicationContext());
}
});
;
}
}
if (jsonStr != null) {
String status = "";
String msg = "";
try {
JSONObject jsonObj = new JSONObject(jsonStr);
runOnUiThread(new Runnable() {
public void run() {
}
});
;
if (jsonObj != null
&& jsonObj.has("status")) {
status = jsonObj.getString("status");
msg = jsonObj.getString("message");
if(jsonObj.has("uid"))
Uid = jsonObj.getString("uid");
System.out.println(jsonObj);
if (status.equals("OK")) {
Intent myIntent = new Intent(
getBaseContext(),
ExtractMenu.class);
startActivityForResult(myIntent, 0);
} else if (status.equals("ERROR")) {
final String errorMsg = msg;
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
errorMsg,
getApplicationContext());
}
});
;
} else {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
"Oops..! something wrong with the service. Please try again Later.",
getApplicationContext());
}
});
;
}
}
} catch (Exception e) {
System.out
.println("Creation of json object failed");
}
}
}
}
}).start();
}
});
signUp.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(this, sign_up.class);
startActivity(intent);
}
}
Looks like something is wrong here. Because, when I'm trying to run this code, my app crashes. It shows the following error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myayubo/com.myayubo.LoginActivity}: java.lang.NullPointerException
But, without intent for signUp button it works.
Here is my logcat.
11-05 10:36:58.359 27532-27532/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myayubo, PID: 27532
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myayubo/com.myayubo.LoginActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.myayubo.LoginActivity.onCreate(LoginActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
            at dalvik.system.NativeStart.main(Native Method)
Please some1 tell me what to do with this error.
Thaks in advance.
-Edit -
Here is the Manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myayubo"
android:versionCode="1"
android:versionName="1.0" >
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--
To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect
option is required to comply with the Google+ Sign-In developer policies
-->
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- To retrieve the account name (email) as part of sign-in: -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<activity
android:name=".Splash"
android:label="Ayubo" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ExtractMenu"
android:label="#string/title_activity_extract_menu" >
</activity>
<activity
android:name=".sign_up"
android:label="#string/title_activity_sign_up" >
</activity>
</application>
</manifest>
you are getting NPE because you are trying to add view which is not in your xml file
signUp = (TextView) findViewById(R.id.signUp);
there is no text view in your xml with this id. check it out if you remove this your code will run perfectly
NullPointerException Because there isn't any TextView with id signUp in activity_login.xml layout.
In your onCreate Method
signUp = (TextView) findViewById(R.id.signUp);
But as your activity_login.xml does not contain TextView with id signUp it return null,
And again you try to set listener on that TextView which is null so NullPointerException
signUp.setOnClickListener(this);
Looks like you fogot to set id here,
<TextView
android:id="#+id/text2" //android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/fbbtn"
android:layout_marginTop="20dp"
android:text="or Sign Up"
android:layout_gravity="center"/>

Categories

Resources