activity doesn't wait untill alertdialog completes - Android Q&A, Help & Troubleshooting

Note: Text content in the code blocks is automatically word-wrapped
package com.connection.phonedetails;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class Test extends Activity {
private static final int REQUEST_CODE = 10;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert);
DatabaseHandler db = new DatabaseHandler(this);
Intent intent = new Intent(this,AlertDialogExample.class);
startActivityForResult(intent,REQUEST_CODE);
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("TYPE");
Toast.makeText(getApplicationContext(),"Your sim type iss POST paidddddddddd", Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(),"Your sim type iss PREEEEE paidddddddddd", Toast.LENGTH_LONG).show();
}
}
}
}
this is alert dialog activity.
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
package com.connection.phonedetails;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AlertDialogExample extends Activity {
// this context will use when we work with Alert Dialog
final Context context = this;
// just for test, when we click this button, we will see the alert dialog.
private Button button;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.alert);
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Select Your SIM Type"); //Set Alert dialog title here
//alert.setMessage("Enter your Name Here"); //Message here
alert.setPositiveButton("Post Paid", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// String value = input.getText().toString();
// Do something with value!
//You will get input data in this variable.
Toast.makeText(getApplicationContext(),"Post Paid", Toast.LENGTH_LONG).show();
//db.addContact(new SimDetails( telephonyManager.getSimSerialNumber(), telephonyManager.getNetworkOperatorName(),"Post"));
Intent returnIntent = new Intent();
returnIntent.putExtra("TYPE","POST Paid");
setResult(RESULT_OK,returnIntent);
finish();
}
});
alert.setNegativeButton("Pre Paid", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(getApplicationContext(),"Pre Paid", Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("TYPE","PRE Paid");
setResult(RESULT_CANCELED,returnIntent);
finish();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
}
/*
@override
public void finish() {
Intent data = new Intent();
// Return some hard-coded values
data.putExtra("TYPE", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
setResult(RESULT_OK, data);
super.finish();
}*/
}
this is working fine.Anyway if added the below two line end Oncreate method of the main activity it doesn't wait untill the alert dialog finishes.it goes to contact activity .So i don't have chance to select option from alert dialog.how to avoid this situation?
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
Intent contact = new Intent(getApplicationContext(),Contacts.class);
startActivity(contact);

Related

[Q] Linking Strings between Activities and WebViews

Hello XDA,
So I've not found anyone properly discussing this. If they do, please link me to the page and don't flame
I've been making an app for my school and so far, I've been doing alright. But now I have run into a problem which seems to be very hard to solve for me alone.
Namely, I have an EditText and a Button in one Activity and a WebView as a different Activity.
I'm trying to get the EditText String into the WebView URL (String being variable, Button initiating the WebView), but get a lot of errors, some not even related to that.
I would really appreciate it if someone could have a look at the code and help me with this
MyWebView.java:
Code:
package bas.sie.Antonius;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebView extends Activity {
WebView mWebView;
EditText mEtxtStudentNum;
static String StudentNumFromHome = bas.sie.Antonius.Home.StudentNum;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl("http://carmelcollegegouda.nl/site_ant/roosters/standaardroosters/Lee1_" + StudentNumFromHome + ".htm");
}
}
Home.java (Homescreen):
Code:
package bas.sie.Antonius;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Home extends Activity {
Button mBtnStSchedule;
static EditText mEtxtStudentNum;
static final String StudentNum = mEtxtStudentNum.getText().toString();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.BtnStSchedule);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MyWebView.class);
startActivityForResult(myIntent, 0);
}
});
// TODO Auto-generated method stub
}
}
AntoniusActivity.java (Main):
Code:
package bas.sie.Antonius;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
public class AntoniusActivity extends TabActivity {
WebView mWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Home.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("home").setIndicator("Home",
res.getDrawable(R.drawable.ic_tab_home))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, External.class);
spec = tabHost.newTabSpec("external").setIndicator("External",
res.getDrawable(R.drawable.ic_tab_external))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, Contact.class);
spec = tabHost.newTabSpec("contact").setIndicator("Contact",
res.getDrawable(R.drawable.ic_tab_contact))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(2);
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
In AntoniusActivity, the private class HelloWebViewClient is underlined with yellow (never used), specifically the bit "HelloWebViewClient".
It's also throwing FC's at startup, and errors in LogCat, but I'll post those later on, as it's 10.30 PM here, and school goes on
Thanks in advance,
bassie1995
No suggestions yet?
How you doin'? Greetings from my GT-I9000!

Q> HELP Connection andrdoid to pc Programming

this is my server code
i am getting an error on my android phone when i clicked the device address
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class ServerSide {
//private static LocalDevice localDevice;
static LocalDevice localDevice;
DiscoveryAgent agent;
private void startServer() throws IOException{
UUID uuid = new UUID("112f8dbf1e46442292b6796539467bc9", false);
String connectionString = "btspp://localhost:" + uuid
+";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
System.out.println("\nServer Started. Waiting for clients to
connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address:
"+dev.getBluetoothAddress());
System.out.println("Remote device name:
"+dev.getFriendlyName(true));
}
public static void main(String[] args) {
//display local device address and name
try{
localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
try{
ServerSide sampleSPPServer=new ServerSide();
sampleSPPServer.startServer();
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
}
}
**************************************************************
and this is my client(android) code
package client.side;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
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.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ClientSideActivity extends Activity {
int REQUEST_ENABLE_BT = 0;
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mArrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
final ListView lv1 = (ListView)findViewById(R.id.listView1);
final TextView out = (TextView)findViewById(R.id.textView1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
}
out.setText(null);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
out.setText("Paired Devices");
Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
mArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
}
lv1.setAdapter(mArrayAdapter);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.setText("Discovered Devices");
mBluetoothAdapter.startDiscovery();
Toast msg = Toast.makeText(ClientSideActivity.this, "Discovering
Devices please wait.", Toast.LENGTH_LONG);
msg.show();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show
in a ListView
mArrayAdapter.add(device.getAddress());
} }
};
// Register the BroadcastReceiver
IntentFilter filter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister
during onDestroy
}
});
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,long id)
{
out.setText(arg0.getItemAtPosition(position).toString());
BluetoothDevice remoteDev = (BluetoothDevice)
arg0.getItemAtPosition(position);
ConnectThread conDev = new ConnectThread(remoteDev);
conDev.start();
}
});
}
public class ConnectThread extends Thread {
private final UUID MY_UUID =
UUID.fromString("112f8dbf1e46442292b6796539467bc9");
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to
mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the
server code
tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the
connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will
block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate
thread)
}
/** Will cancel an in-progress connection, and close the
socket */
}
}

[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

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

Categories

Resources