Fatal Exception startactivity in Android studio - android-studio

I am totally new at Android / Java. and i have some project school and i have this code
```
package com.example.utsmobileprograming;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText etinput;
CheckBox ckkotak, cksegitiga;
Button btkirim;
//membuat variabel object tipe data Proses
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etinput=(EditText) findViewById(R.id.editTextTextInput);
ckkotak=(CheckBox) findViewById(R.id.checkBoxKotak);
cksegitiga=(CheckBox) findViewById(R.id.checkBoxSegitiga);
btkirim=(Button) findViewById(R.id.buttonKirim);
btkirim.setOnClickListener(v -> {
Intent intentbentuk = new Intent(getApplicationContext(), ActivityHasil.class);
intentbentuk.putExtra("inputan", etinput.getText().toString());
intentbentuk.putExtra("kotak", ckkotak.isChecked());
intentbentuk.putExtra("segitiga", cksegitiga.isChecked());
startActivity(intentbentuk);
});
}
}
```
but i didn't find my error because i see this the log in my android studio
2022-05-14 03:28:34.002 6525-6525/com.example.utsmobileprograming E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utsmobileprograming, PID: 6525
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.utsmobileprograming/com.example.utsmobileprograming.ActivityHasil}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2065)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1727)
at android.app.Activity.startActivityForResult(Activity.java:5314)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:597)
at android.app.Activity.startActivityForResult(Activity.java:5272)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:583)
at android.app.Activity.startActivity(Activity.java:5658)
at android.app.Activity.startActivity(Activity.java:5611)
at com.example.utsmobileprograming.MainActivity.lambda$onCreate$0$com-example-utsmobileprograming-MainActivity(MainActivity.java:32)
how to solve this? is the startActivity my problem ?

You have to add ActivityHasil to your AndroidManifest.xml file like following
<activity android:name="ActivityHasil" android:exported="false"/>

Related

Mockito.when method doesn't manage my service call

i'm trying to make Unit Test testing a simple GET controller method apply MockMvc.perform method but when the controller receive a request the method Mockito.when seems to doesn't manage the method call of MenuService and the test throw an exception. The Exception says menuServiceMock is null
I'm working with Mockito MockMvc JUnit
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import edu.AG.LandingPageSanpietro.domain.Menu;
import edu.AG.LandingPageSanpietro.service.MenuService;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
class MenuControllerTest {
private MockMvc mockMvc;
#Autowired
private MenuService menuServiceMock;
#Test
public void testHomeController1() throws Exception {
Menu first=new Menu("titolo1","descrizione1","filename1");
Menu second=new Menu("titolo2","descrizione2","filename2");
Mockito.when(menuServiceMock.getMenus()).thenReturn(Arrays.asList(first, second));
mockMvc.perform(get("/manageMenu"))
.andExpect(status().isOk())
.andExpect(view().name("manageMenu"))
.andExpect(forwardedUrl("/src/main/resources/tamplates/manageMenu.html"))
.andExpect(model().attribute("menus", hasSize(2)));
}
My Controller
#GetMapping("/manageMenu")
public String chiamataGestisciMenu(Model model) {
model.addAttribute("menus", menuService.getMenus());
return "manageMenu";
}
The error
java.lang.NullPointerException: Cannot invoke "edu.AG.LandingPageSanpietro.service.MenuService.getMenus()" because "this.menuServiceMock" is null
at edu.AG.LandingPageSanpietro.controller.MenuControllerTest.testHomeController1(MenuControllerTest.java:44)
I can't understand why when() method doesn't manage my menuServiceMock.getMenus() request for returning the specified list.
Use the annotation #Mock from mockito instead of #Autowired.
Seems like you have not initialized MockMvc. Try Autowiring it or initialize it in #Before method:
#RunWith(SpringJUnit4ClassRunner.class)
#WebMvcTest(controllers = ControllerToBeTested.class)
class MenuControllerTest {
#Autowired
private MockMvc mockMvc;
...
or you can even initialize it in #Before lik this:
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ControllerToBeTested()).build();
}

Can one reference id directly in kotlin?My small program can't seem to run

Hi im new in android and i read that i can directly reference id from activity_main to mainAcctivity.kt without using findviewbyid.When i do that i get an error but my ids are correct:
This is the error Unresolved reference: button and Unresolved reference: textView
This is my code
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get reference to button
//val btnClickMe = findViewById(R.id.button) as Button
//val myTextView = findViewById(R.id.textView) as TextView
var timesClicked = 0
// set on-click listener
button.setOnClickListener {
timesClicked += 1
textView.text = timesClicked.toString()
Toast.makeText(this#MainActivity, "Hello Don.", Toast.LENGTH_SHORT).show()
}
}
}```
Please help out,i tried to import android.widget.button and textView that option is not available but when i hardcode the text appears inactive.
You can make use of ViewBinding to reduce the use of findViewById. You can find an example here.
You can go through this blog to have more insight on how to use ViewBinding.
For the above code, you can resolve the issue using the code below:
val myTextView = findViewById<TextView>(R.id.textView)
val btnClickMe = findViewById<Button>(R.id.button)

fragment.show(fragmentManager,"confirmDelete") error

Please help me, I'm new to kotlin programming. Since this morning i have this problem and I can't solve it. I don't understand the error, ... This is this line of code: fragment.show (fragmentManager, "confirmDelete")
enter image description here
MainActivity.kt
import android.app.PendingIntent.getActivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.graphics.Typeface
import androidx.core.app.ComponentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.util.Log
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val user = User("ACHAKA", "Eric", 26)
val button1 = findViewById<View>(R.id.button1)
button1.setOnClickListener {
println("Start 2nd activity")
val intent = Intent(this, GreenActivity::class.java)
intent.putExtra("user", user)
startActivity(intent)
}
findViewById<View>(R.id.button2).setOnClickListener{
val fragment = ConfirmDeleteDialogFragment()
fragment.listener = object: ConfirmDeleteDialogFragment.ConfirmDeleteListener {
override fun onDialogPositiveClick() {
Log.i("MainActivity", "onDialogPositiveClick()")
}
override fun onDialogNegativeClick() {
Log.i("MainActivity", "onDialogNegativeClick()")
}
}
fragment.show(fragmentManager,"confirmDelete")
}
}
}
ConfirmDeleteDialogFragment.kt
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.DialogFragment
class ConfirmDeleteDialogFragment: DialogFragment() {
interface ConfirmDeleteListener {
fun onDialogPositiveClick()
fun onDialogNegativeClick()
}
val TAG = ConfirmDeleteDialogFragment::class.java.simpleName
var listener: ConfirmDeleteListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
builder.setMessage("Supprimer tout le contenu du téléphone ?")
.setPositiveButton("Oh oui !", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, id: Int) {
Log.i(TAG, "Youpi ! on va tout casser")
listener?.onDialogPositiveClick()
}
})
.setNegativeButton("Euh... Non", DialogInterface.OnClickListener { dialog, id ->
Log.i(TAG, "Bon ben ce sera pour la prochaine fois")
dialog.dismiss()
listener?.onDialogNegativeClick()
})
return builder.create()
}
}
Logcat (error)
:55:54.868 25808-25808/aea.com E/Zygote: v2
2019-12-23 00:55:54.883 25808-25808/aea.com E/Zygote: accessInfo : 0
2019-12-23 00:55:57.485 25808-25808/aea.com E/AndroidRuntime: FATAL EXCEPTION: main
Process: aea.com, PID: 25808
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.fragment.app.FragmentTransaction androidx.fragment.app.FragmentManager.beginTransaction()' on a null object reference
at androidx.fragment.app.DialogFragment.show(DialogFragment.java:142)
at aea.com.MainActivity$onCreate$2.onClick(MainActivity.kt:42)
at android.view.View.performClick(View.java:6207)
at android.view.View$PerformClick.run(View.java:23639)
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:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
fragmentManager is deprecated:
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*
* #deprecated Use {#link android.support.v4.app.FragmentActivity#getSupportFragmentManager()}
*/
#Deprecated
public FragmentManager getFragmentManager() {
return mFragments.getFragmentManager();
}
So you must use supportFragmentManager instead of fragmentManager.
It will not be compiled if you use fragmentManager (as marked red line, it seems on your screenshot too).
Thank you supportFragmentManager solved my problem well. :)
fragment.show(supportFragmentManager ,"confirmDelete")

How to register an app for Sony Smart Glass?

I was trying to develop an app in Android Studio 2.1.2 for Sony Smart Glass. I wrote the coding and now I have to register the app so that the Smart Connect can recognize the app, so that it can be used for Sony Smart Glass.
Sony has given few set of instructions to register but I couldn't understand it. Nevertheless I tried my best to register it. I am getting around 13 errors. I have posted my coding below.
package com.example.balakrishnan.newapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements RegistrationInformation {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButonTap(View v) {
Toast myToast = Toast.makeText(getApplicationContext(), "sony smart glass", Toast.LENGTH_LONG);
myToast.show();
}
public void browserapp(View view) {
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://192.168.72.101/smartglass/datetime.php"));
startActivity(browserIntent);
}
#Override
public int getRequiredControlApiVersion() {
return 4;
}
#Override
public int getTargetControlApiVersion() {
return 4;
}
#Override
public int getRequiredSensorApiVersion() {
// Return 0 if the API is not required for your app
return 0;
}
#Override
public boolean isDisplaySizeSupported(int width, int height) {
boolean isSEG =
(width == HelloLayoutsSEGControl.getSupportedControlWidth(mContext) &&
height == HelloLayoutsSEGControl.getSupportedControlHeight(mContext));
return isSW2 || isSEG;
}
#Override
protected RegistrationInformation getRegistrationInformation() {
return new SampleRegistrationInformation(this);
}
}
Errors:
Error:(13, 64) error: cannot find symbol class RegistrationInformation
Error:(60, 15) error: cannot find symbol class RegistrationInformation
Error:(37, 5) error: method does not override or implement a method from a supertype
Error:(31, 5) error: method does not override or implement a method from a supertype
Error:(43, 5) error: method does not override or implement a method from a supertype
Error:(49, 5) error: method does not override or implement a method from a supertype
Error:(52, 75) error: cannot find symbol variable mContext
Error:(52, 27) error: cannot find symbol variable HelloLayoutsSEGControl
Error:(53, 84) error: cannot find symbol variable mContext
Error:(53, 35) error: cannot find symbol variable HelloLayoutsSEGControl
Error:(55, 16) error: cannot find symbol variable isSW2
Error:(59, 5) error: method does not override or implement a method from a supertype
Error:(61, 20) error: cannot find symbol class SampleRegistrationInformation
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Follow these steps for registration process:
Create a class that extends RegistrationInformation.
Override the methods to define the API versions used.
Override the getExtensionRegistrationConfiguration() method to define your app’s registration info.
Override the isDisplaySizeSupported() method to define which accessories your app supports.
Return an instance of RegistrationInformation in your ExtensionService class.

Very basic Spinner issue with Android AIDE

Hi I'm completely new to android programming and use AIDE via tablet.
I'm trying to create a very basic program with a Spinner box that gives output on the selection Ive made via an TextView or System.Out.printIn. (Perhaps the next step up from Hello world - if you will)
For some reason that I cannot fathom,the compiler refuses to recognise the OnClickListener and gives the error message 'Unknown method OnClickListener in Android.Widget.Spinner'
When I have already checked this in the imports.
As a matter of interest I have changed the name of the Spinner and the error seems to dissapear, the problem then is the Spinner name. I have tried several variations on this, and have came to the conclusion that the best option for me is to create a variable just after Main Acivity, and before the layout is declared.
I have also disabled one of the overrides in order to resolve my problem
has anyone got an idea what the problem could be?
package com.BGilbert.AUC;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.View.OnClickListener;
import android.widget.Spinner.*;
import android.view.*;
public class MainActivity extends Activity {;
String Fbstring;
OnClickListener Myonclick;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
final Spinner Fbspinner=(Spinner)findViewById(R.id.Spinner);
// The problem is with this line. OnClickListener just wont be
// recognised
Fbspinner.OnClickListener(Myonclick);
}
// Override previously disabled
#Override
public void Onselect(AdapterView<?> parent,View V, int pos, long id) {
Fbstring = parent.getItemAtPosition(pos).toString();
System.out.println(Fbstring);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
You can't set an onClickListener on a spinner, only on it's views which is too advanced for you at the moment. Instead, use an onItemSelectedListener.
public class MainActivity extends Activity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
...
...
}
You should read the documentation first http://developer.android.com/guide/topics/ui/controls/spinner.html
Also try to use standard naming conventions:
http://www.oracle.com/technetwork/java/codeconv-138413.html
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
Finally, you have many problems in this code, e.g.
public class MainActivity extends Activity {;
Note the semicolon at the end.
Get your code compiling first, then come back with your next question.
Good luck

Resources