[JAVA PROBLEM] Successfull compiled app crashes, - Android Q&A, Help & Troubleshooting

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

Related

Trouble with Service and startForeground()

I have trouble creating a service for a mediaplayer. I would like to have startforeground instead of this as well. But I have no proof of my service running. So I dont know if my code actually works. Can someone help me?
If someone is able to help me completely setting up my service, I may pay €5-10. I received €50 from the company to set up a developer account. So I have €25 left.
I am creating a streaming app for a radio station to listen to the internet stream.
Code:
package jonashendrickx.radioplayer.rgrfm;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class RadioService extends Service {
private final IBinder mBinder = new RadioBinder();
@Override
public void onCreate() {
Toast.makeText(this, "Let's Go", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent arg0) {
Log.e("LocalService", "Launched");
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
public class RadioBinder extends Binder {
RadioService getService() {
return RadioService.this;
}
}
}
Code:
package jonashendrickx.radioplayer.rgrfm;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
mRadioService = ((RadioService.RadioBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName className) {
mRadioService = null;
}
};
private RadioService mRadioService;
private boolean mIsBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doBindService();
}
@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
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
void doBindService() {
bindService(new Intent(this, RadioService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
Log.e("", "service started");
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
}

trouble with startForeground and notification showing.

I have already service up and running. So that is working well. Now I am stuck with startForeground. My notifications dont seem to show so I believe startForeground isnt working as well.
I am developing for API range 10-17
I already tried several tutorials without luck
Is someone willing to help me out?
http://www28.zippyshare.com/v/73408891/file.html
Code:
package jonashendrickx.radioplayer.rgrfm;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class RadioService extends Service implements OnErrorListener {
private final IBinder mBinder = new RadioBinder();
private MediaPlayer mMediaPlayer;
private final String[] mirrors = {
"http://stream.intronic.nl/rgrfm",
"http://shoutcast01.edpnet.net:10210"
};
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
@Override
public void onCreate() {
initializeMediaPlayer();
startPlaying();
}
@Override
public void onDestroy() {
stopPlaying();
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.stop();
mp.release();
return false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
private void initializeMediaPlayer() {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(mirrors[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startPlaying() {
try {
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.prepareAsync();
} catch (IllegalStateException ex) {
ex.printStackTrace();
return;
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
}
private void stopPlaying() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.release();
initializeMediaPlayer();
}
}
public class RadioBinder extends Binder {
RadioService getService() {
return RadioService.this;
}
}
}
Code:
package jonashendrickx.radioplayer.rgrfm;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnClickListener {
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
mRadioService = ((RadioService.RadioBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName className) {
mRadioService = null;
mToggleButtonMediaPlayer.setChecked(false);
}
};
private RadioService mRadioService;
private boolean mIsBound;
private ToggleButton mToggleButtonMediaPlayer;
@Override
public void onClick(View view) {
if (view.equals(mToggleButtonMediaPlayer)) {
if (mRadioService == null) {
doBindService();
} else {
doUnbindService();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToggleButtonMediaPlayer = (ToggleButton)findViewById(R.id.toggleButtonMediaPlayer);
mToggleButtonMediaPlayer.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
void doBindService() {
bindService(new Intent(this, RadioService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
}
djjonastybe said:
I have already service up and running. So that is working well. Now I am stuck with startForeground. My notifications dont seem to show so I believe startForeground isnt working as well.
I am developing for API range 10-17
I already tried several tutorials without luck
Is someone willing to help me out?
http://www28.zippyshare.com/v/73408891/file.html
Click to expand...
Click to collapse
Where do you call startForeground? I can see just bind.
EDIT: I did not check the zip file as I never download any files if I don't know whether I can trust them. Nothing against you.
EDIT: You could try something like this: (I didn't test it)
Code:
private static final int NOTIFICATION_ID = 7392749; //value doen't matter
@Override
public void runInForeground() {
Notification n = new Notification(R.drawable.ic_launcher, "music is playing", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(this, 0, null, 0);
n.setLatestEventInfo(this, "Music Player", "Playing some music", i);
startForeground(NOTIFICATION_ID, n);
}
EDIT: You could also check out this project: https://github.com/commonsguy/cw-android/tree/master/Notifications/FakePlayer

First App dev. help

Hello I'm Trying to learn my firsy app (Flash Lifght app) ..
I understand that i need to give app permissions etc.
Can some one expaine me how do i need to do that when im opening new project.
I what is code or the file i need to paste the code..
Sorry for bad english and thanks for helping!
natan.p said:
Hello I'm Trying to learn my firsy app (Flash Lifght app) ..
I understand that i need to give app permissions etc.
Can some one expaine me how do i need to do that when im opening new project.
I what is code or the file i need to paste the code..
Sorry for bad english and thanks for helping!
Click to expand...
Click to collapse
You need to set the permissions in the AndroidManifest.xml file add a uses permission and under that class an android:name= *camera*
Regards
MasterAwesome
MasterAwesome said:
You need to set the permissions in the AndroidManifest.xml file add a uses permission and under that class an android:name= *camera*
Regards
MasterAwesome
Click to expand...
Click to collapse
I have an error i found tutorial how create flash light app i cop all codes ti manifest etc files but i have error with the java file........
the error: The public type FlashlightActivity must be defined in its own file.
the code: Press Control + F and search this line public class FlashlightActivity extends Activity {
PHP:
package com.natan.flashlight;
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;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.widget.ToggleButton;
/**
* @author Prabu
* July 30 2013
* @version 1.0
*
*/
public class FlashlightActivity extends Activity { // <--------------------------------------- There are the error..
private Camera camera;
private ToggleButton button;
private final Context context = this;
//@see android.app.Activity#onStop()
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.flashlight);
button = (ToggleButton) findViewById(R.id.togglebutton);
final PackageManager pm = context.getPackageManager();
if(!isCameraSupported(pm)){
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera");
alertDialog.setMessage("The device's doesn't support camera.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's doesn't support camera.");
}
});
alertDialog.show();
}
camera = Camera.open();
}
public void onToggleClicked(View view) {
PackageManager pm=context.getPackageManager();
final Parameters p = camera.getParameters();
if(isFlashSupported(pm)){
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
} else {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
}
}else{
button.setChecked(false);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera Flash");
alertDialog.setMessage("The device's camera doesn't support flash.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's camera doesn't support flash.");
}
});
alertDialog.show();
}
}
/**
* @param packageManager
* @return true <b>if the device support camera flash</b><br/>
* false <b>if the device doesn't support camera flash</b>
*/
private boolean isFlashSupported(PackageManager packageManager){
// if device support camera flash?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
return true;
}
return false;
}
/**
* @param packageManager
* @return true <b>if the device support camera</b><br/>
* false <b>if the device doesn't support camera</b>
*/
private boolean isCameraSupported(PackageManager packageManager){
// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
}
return false;
}
}
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();
}
}
@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;
}
}
}
natan.p said:
I have an error i found tutorial how create flash light app i cop all codes ti manifest etc files but i have error with the java file........
the error: The public type FlashlightActivity must be defined in its own file.
the code: Press Control + F and search this line public class FlashlightActivity extends Activity {
PHP:
package com.natan.flashlight;
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;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.widget.ToggleButton;
/**
* @author Prabu
* July 30 2013
* @version 1.0
*
*/
public class FlashlightActivity extends Activity { // <--------------------------------------- There are the error..
private Camera camera;
private ToggleButton button;
private final Context context = this;
//@see android.app.Activity#onStop()
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.flashlight);
button = (ToggleButton) findViewById(R.id.togglebutton);
final PackageManager pm = context.getPackageManager();
if(!isCameraSupported(pm)){
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera");
alertDialog.setMessage("The device's doesn't support camera.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's doesn't support camera.");
}
});
alertDialog.show();
}
camera = Camera.open();
}
public void onToggleClicked(View view) {
PackageManager pm=context.getPackageManager();
final Parameters p = camera.getParameters();
if(isFlashSupported(pm)){
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
} else {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
}
}else{
button.setChecked(false);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("No Camera Flash");
alertDialog.setMessage("The device's camera doesn't support flash.");
alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
Log.e("err", "The device's camera doesn't support flash.");
}
});
alertDialog.show();
}
}
/**
* @param packageManager
* @return true <b>if the device support camera flash</b><br/>
* false <b>if the device doesn't support camera flash</b>
*/
private boolean isFlashSupported(PackageManager packageManager){
// if device support camera flash?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
return true;
}
return false;
}
/**
* @param packageManager
* @return true <b>if the device support camera</b><br/>
* false <b>if the device doesn't support camera</b>
*/
private boolean isCameraSupported(PackageManager packageManager){
// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
}
return false;
}
}
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();
}
}
@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
You can't have 2 public class in the same file.. Create a new class
Regards
MasterAwesome
MasterAwesome said:
You can't have 2 public class in the same file.. Create a new class
Regards
MasterAwesome
Click to expand...
Click to collapse
What you mean two public classes?
Sent from my Nexus 5 using Tapatalk
natan.p said:
What you mean two public classes?
Sent from my Nexus 5 using Tapatalk
Click to expand...
Click to collapse
Main activity and flashlight.. Just remove the public for flashlight
Regards
MasterAwesome

[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

Android Studio Noob Question: Btn 2 Activity

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"); //
}
}

Categories

Resources