Android Studio Noob Question: Btn 2 Activity - Android Q&A, Help & Troubleshooting

Hey Im very new to Android studio, and Im trying to understand the procces of building a app
So here is what I learned so far.
1. I start with the MainActivty
2. Add Activity Cycle: onCreate, onStart, onResume etc.
3. Import android.util.Log; so I can see the log information for my code
4. Create a Second Activity
5. Create a btn on the MainActivity and onClick move to Second Activity.
Check the code below to say how I set up my MainActivity
Now here is the problem, when i run the Emulator:
- there are no errors
Press button to go to the other Activity, my log shows:
MainActivity_message: onClick
MainActivity_message: onPause
SecondActivity_message: onCreate
SecondActivity_message: onStart
SecondActivity_message: onResume
BUT, in my Emulator viewer the MainActivity stays visible and Im not seeing the SecondAcivity.
How do i solve this or what im I missing here?
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button BtnMove; //
public static final String TAG = "MainActivity_message";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate"); //
BtnMove = findViewById(R.id.BTNActivityOne); //
BtnMove.setOnClickListener(new View.OnClickListener() { //
@override
public void onClick(View v) {
moveToActivityTwo(); //
Log.i(TAG, "onClick"); //
}
});
}
private void moveToActivityTwo() { //
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
@override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart"); //
}
@override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume"); //
}
@override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause"); //
}
@override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop"); //
}
@override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart"); //
}
@override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy"); //
}
}

Related

[Q] BroadcastReceiver question

The first version of a small program. MyBroadcastReceiver is invoked by sendBroadcast(new Intent(MyBroadcastReceiver.ACTION)). It works.
Code:
package com.example.broadcast;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity
{
private final BroadcastReceiver mBroadcastReceiver = new MyBroadcastReceiver();
private class MyBroadcastReceiver extends BroadcastReceiver
{
public static final String ACTION = "com.example.broadcast.MyBroadcastReceiver.ACTION";
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "onReceive() fired", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(mBroadcastReceiver, new IntentFilter(MyBroadcastReceiver.ACTION));
((Button)findViewById(R.id.testButton)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
sendBroadcast(new Intent(MyBroadcastReceiver.ACTION));
}
});
}
@Override
protected void onDestroy()
{
unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}
The second version of the same program. Now MyBroadcastReceiver is invoked by sendBroadcast(new Intent(MyActivity.this, MyBroadcastReceiver.class)) and IntentFilter in call to registerReceiver() is empty. It doesn't work. Why? And what do I have to change to make it work?
Code:
public class MyActivity extends Activity
{
private final BroadcastReceiver mBroadcastReceiver = new MyBroadcastReceiver();
private class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "onReceive() fired", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(mBroadcastReceiver, new IntentFilter());
((Button)findViewById(R.id.testButton)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
sendBroadcast(new Intent(MyActivity.this, MyBroadcastReceiver.class));
}
});
}
@Override
protected void onDestroy()
{
unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
}

[Q] Camera stream

Hi,
I have to develop an application for my studies which consists in capture and broadcasting live on Web via an android phone
At present my code allows me to capture but I do not manage to broadcast the video on a server
Can you help me ?
Code:
package com.androidvideocapture;
import java.io.IOException;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class AndroidVideoCapture extends Activity implements SurfaceHolder.Callback{
Button myButton;
MediaRecorder mediaRecorder;
SurfaceHolder surfaceHolder;
boolean recording;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recording = false;
mediaRecorder = new MediaRecorder();
initMediaRecorder();
setContentView(R.layout.activity_android_video_capture);
SurfaceView myVideoView = (SurfaceView)findViewById(R.id.videoview);
surfaceHolder = myVideoView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
myButton = (Button)findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}
private Button.OnClickListener myButtonOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(recording){
mediaRecorder.stop();
mediaRecorder.release();
finish();
}else{
mediaRecorder.start();
recording = true;
myButton.setText("STOP");
}
}};
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
prepareMediaRecorder();
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
private void initMediaRecorder(){
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mediaRecorder.setProfile(camcorderProfile_HQ);
mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
}
private void prepareMediaRecorder(){
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

[JAVA PROBLEM] Successfull compiled app crashes,

Anyone see what im doing wrong here? im new to java so i dont have a clue..
successfully compiles without a problem but crashes on start, the blue code i have added
Code:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
[COLOR=DeepSkyBlue]import android.widget.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;[/COLOR]
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
[COLOR=DeepSkyBlue] Button startpatching = (Button)findViewById(R.id.start);
startpatching.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Process proc = Runtime.getRuntime().exec("/data/local/startpatch.sh /");
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}}
});
};[/COLOR]
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Probably would be wise to include the stack trace...
ricky310711 said:
Anyone see what im doing wrong here? im new to java so i dont have a clue..
successfully compiles without a problem but crashes on start, the blue code i have added
Code:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
[COLOR=DeepSkyBlue]import android.widget.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;[/COLOR]
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
[COLOR=DeepSkyBlue] Button startpatching = (Button)findViewById(R.id.start);
startpatching.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Process proc = Runtime.getRuntime().exec("/data/local/startpatch.sh /");
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}}
});
};[/COLOR]
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Click to expand...
Click to collapse
Post a log/stacktrace as jcase suggested and also the content of activity_main.xml
jcase said:
Probably would be wise to include the stack trace...
Click to expand...
Click to collapse
Jonny said:
Post a log/stacktrace as jcase suggested and also the content of activity_main.xml
Click to expand...
Click to collapse
thanks guy, got it working but

[Q] App crashes after sending a message using sockets

I'm developing a simple chat app and it just stops after transmitting the message. The Server shows the message that means that it is sent successfully but my app crashes after that. This is the Client code :
Code:
package com.example.androidpc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Chat extends Activity {
Socket socket;
EditText msg_txt;
TextView chatfield_tv;
Button send_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
msg_txt = (EditText) findViewById(R.id.msg_txt);
chatfield_tv = (TextView) findViewById(R.id.chatfield_tv);
send_btn = (Button) findViewById(R.id.send_btn);
socket = SocketWrapper.getSocket();
send_btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new chatIO().execute();
}
});
}
private class chatIO extends AsyncTask<String,String,String>{
PrintStream ps;
Scanner scan;
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
ps = new PrintStream(socket.getOutputStream());
ps.println(msg_txt.getText().toString());
publishProgress("you");
scan = new Scanner(socket.getInputStream());
publishProgress("i");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
if(values[0].equals("you"))
{
chatfield_tv.append("You : "+msg_txt.getText().toString());
msg_txt.setText("");
}
else
{
chatfield_tv.append("Server : "+scan.nextLine());
}
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
ps.flush();
scan.close();
super.onPostExecute(result);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't have a logcat since i don't test on an emulator or adb

hELP- .getSpeed();

HELLO , HOW CAN I FIND SPEED AND DISTANCE TRAVELED? HOW CAN I MARK THE DISPLACEMENT ON THE MAP ?
….
therricately I could find it that way with this function..... but it's okay, it's ignored.
Code:
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
float v= location.getSpeed();
}
api 19
Code:
package com.example.mps;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
public class MapsActivity extends FragmentActivity
implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// TODO: Before enabling the My Location layer, you must request
// location permission from the user. This sample does not include
// a request for location permission.
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}

Categories

Resources