This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am creating my second app and having issues.
My app works fine without inputting code for a button to function.
But when I do, it crashes. The app doesn't even open.
What is going on?
I tried rearranging and it still doesn't work.
The buttons are used to combine EditText
They work on a different app but when I try to combine it with this code it fails.
package com.glenn.howtowritefantasy.activities;
import com.glenn.howtowritefantasy.R;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
Button btn_Combine,btn_Clear;
EditText Tagline_p2,Start_writing_p1,
Part_three1,Part_four1,Part_five1;
TextView tv_Result;
//THIS IS WHERE THE PROBLEM STARTS
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tagline_p2= (EditText) findViewById(R.id.tagline_p2);
Start_writing_p1= (EditText) findViewById(R.id.start_writing_p1);
Part_three1= (EditText) findViewById(R.id.part_three1);
Part_four1= (EditText) findViewById(R.id.part_four1);
Part_five1= (EditText) findViewById(R.id.part_five1);
tv_Result= (TextView) findViewById(R.id.tv_result);
btn_Combine= (Button) findViewById(R.id.btn_combine);
btn_Clear= (Button) findViewById(R.id.btn_clear);
btn_Clear.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
btn_Clear.setBackgroundColor(Color.DKGRAY);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
btn_Clear.setBackgroundColor(Color.BLUE);
}
return false;
}
});
btn_Combine.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
btn_Combine.setBackgroundColor(Color.DKGRAY);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
btn_Combine.setBackgroundColor(Color.BLUE);
}
return false;
}
});
//THIS IS WHERE THE PROBLEM ENDS
// Check operating system version and set the layout file based on the outcome
if(Build.VERSION.SDK_INT == 18 || Build.VERSION.SDK_INT == 19)
{
setContentView(R.layout.activity_main_no_material);
}
else
{
setContentView(R.layout.activity_main);
}
init();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.character_development:
Intent intentCharDev = new Intent(this, CharacterDevActivity.class);
startActivity(intentCharDev);
break;
case R.id.the_world:
Intent intentWorld = new Intent(this, TheWorldActivity.class);
startActivity(intentWorld);
break;
case R.id.the_magic:
Intent intentMagic = new Intent(this, TheMagicActivity.class);
startActivity(intentMagic);
break;
case R.id.creatures_races:
Intent intentCreaturesRaces = new Intent(this, CreaturesRacesActivity.class);
startActivity(intentCreaturesRaces);
break;
case R.id.story_development:
Intent intentStoryDev = new Intent(this, StoryDevActivity.class);
startActivity(intentStoryDev);
break;
case R.id.btn_combine:
//Toast.makeText(MainActivity.this,"combine",Toast.LENGTH_SHORT).show();
String first=Tagline_p2.getText().toString();
String last=Start_writing_p1.getText().toString();
String unew= Part_three1.getText().toString();
String blast=Part_four1.getText().toString();
String end= Part_five1.getText().toString();
if (TextUtils.isEmpty(first)){
Tagline_p2.setError("please enter your first name");
return;
}
if (TextUtils.isEmpty(last)){
Start_writing_p1.setError("please enter your last name");
return;
}
if (TextUtils.isEmpty(unew)){
Part_three1.setError("please enter your something");
return;
}
if (TextUtils.isEmpty(unew)){
Part_four1.setError("please enter your something");
return;
}
if (TextUtils.isEmpty(unew)){
Part_five1.setError("please enter your something");
return;
}
String full=first+" "+last+" "+unew+" " +blast+" " +end;
tv_Result.setText(""+full);
break;
case R.id.btn_clear:
//Toast.makeText(MainActivity.this,"Clear",Toast.LENGTH_SHORT).show();
Tagline_p2.setText("");
Start_writing_p1.setText("");
Part_three1.setText("");
Part_four1.setText("");
Part_five1.setText("");
tv_Result.setText("");
break;
}
}
private void init(){
this.setSupportActionBar((Toolbar) findViewById(R.id.tb_menu));
this.getSupportActionBar().setTitle("Write Fantasy");
findViewById(R.id.character_development).setOnClickListener(this);
findViewById(R.id.the_world).setOnClickListener(this);
findViewById(R.id.the_magic).setOnClickListener(this);
findViewById(R.id.creatures_races).setOnClickListener(this);
findViewById(R.id.story_development).setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handles events from the options menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.item_1:
sendRequestEmail();
return true;
case R.id.item_2:
sendEmail();
return true;
case R.id.item_3:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Sends email to timo24apps#gmail.com to request content
*/
private void sendRequestEmail(){
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:timo24apps#gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "How to Write Fantasy: Request Content");
i.putExtra(Intent.EXTRA_TEXT , "Please describe what content you would like to see added or feel free to give me any suggestions for improving the app! I'm also available to read a chapter or two from your story and give some feedback!" + System.getProperty("line.separator") + System.getProperty("line.separator") + "**********************" + System.getProperty("line.separator") + System.getProperty("line.separator"));
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
/**
* Sends email to timo24apps#gmail.com to report problem
*/
private void sendEmail(){
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:timo24apps#gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "How to Write Fantasy: Report Problem");
i.putExtra(Intent.EXTRA_TEXT , "Please describe what problem you encountered or feel free to give me any suggestions for improving the app!" + System.getProperty("line.separator") + System.getProperty("line.separator") + "**********************" + System.getProperty("line.separator") + System.getProperty("line.separator"));
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
Here are the logcat errors:
Process: com.glenn.howtowritefantasy, PID: 5705
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.glenn.howtowritefantasy/com.glenn.howtowritefantasy.activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
Check if a Button with btn_clear id exists in your activity_main.xml file. If so , check if the id declarations is like this: android:id="#+id/btn_clear" *With the +signal
Related
I used Ucrop to crop an image from camera, but the activity skips. Here is my MainActivity.java file. I think i'm missing something. My code is little bit longer, please take a look. Thanks in advance.
package com.example.sathwik.uploadtrail1;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.yalantis.ucrop.UCrop;
public class MainActivity extends AppCompatActivity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
/**
Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
checking device has camera hardware or not
*/
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);// set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/** Perform UCrop */
public void performUcrop(){
UCrop.of(fileUri, fileUri).start(this);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState (Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
performUcrop();
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
//launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(), "Sorry! Failed to record video", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(Config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menuLogout) {
logout();
}
return super.onOptionsItemSelected(item);
}
}
I added Ucrop libraries in my gradle file. My gradle app module has this
compile 'com.github.yalantis:ucrop:2.2.1-native'
Android monitor shows this log
07-02 00:42:22.953 1534-2050/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.954 1534-2050/system_process V/WindowManager: addAppToken: AppWindowToken{2e96b812 token=Token{39e8cb9d ActivityRecord{22ae1a74 u0 com.example.sathwik.uploadtrail1/com.yalantis.ucrop.UCropActivity t29}}} to stack=1 task=29 at 2
07-02 00:42:22.959 1534-1955/system_process I/ActivityManager: START u0 {cmp=com.example.sathwik.uploadtrail1/.UploadActivity (has extras)} from uid 10058 on display 0
07-02 00:42:22.962 1534-1955/system_process V/WindowManager: addAppToken: AppWindowToken{278b8499 token=Token{39cc69e0 ActivityRecord{322e0be3 u0 com.example.sathwik.uploadtrail1/.UploadActivity t29}}} to stack=1 task=29 at 3
07-02 00:42:23.578 14053-14053/com.example.sathwik.uploadtrail1 I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
07-02 00:42:23.945 1534-1836/system_process V/WindowManager: Adding window Window{14ab833f u0 com.example.sathwik.uploadtrail1/com.example.sathwik.uploadtrail1.UploadActivity} at 6 of 11 (after Window{14c5edfe u0 com.android.camera/com.android.camera.Camera})
07-02 00:42:24.332 1534-1563/system_process I/ActivityManager: Displayed com.example.sathwik.uploadtrail1/.UploadActivity: +1s293ms
07-02 00:42:24.333 1534-1558/system_process I/ActivityManager: Killing 2721:com.google.android.gms.unstable/u0a7 (adj 15): empty for 3423s
07-02 00:42:24.333 1534-1558/system_process W/libprocessgroup: failed to open /acct/uid_10007/pid_2721/cgroup.procs: No such file or directory
07-02 00:42:25.366 2376-14273/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.
07-02 00:42:25.374 1534-1836/system_process I/ActivityManager: Killing 9541:com.android.calendar/u0a18 (adj 15): empty for 2545s
07-02 00:42:25.374 1534-1836/system_process W/libprocessgroup: failed to open /acct/uid_10018/pid_9541/cgroup.procs: No such file or directory
UCrop is working fine, but you are starting it the wrong way, if you specify the same argument for source and destination, the onActivityResult will be called immediately. and obviously with no result, fix:
1. specify different source and destination
UCrop.of(fileUri, dstUri).start(this);
2. add the code to handle the response from uCrop. in my tutorial
https://youtu.be/glwM0cAUV4A, the code in onActivityResult is not perfect but it works.
The code is heavily borrowed from https://github.com/hastarin/android-udpsender and where his code is very versatile, I want a simple way to send a udp packet to an Arduino that will unlock a garage door.
Basically page one (MainActivity) has a big "Open" button and a small "Set Params" button. Page two (Main2Activity) is mostly the borrowed code with lots deleted and provides a way to input the IP address, port and the unlock code word. Currently there is "Send" button that sends the assembled udp packet to the client and it works as intended.
The issue is that I really don't want to have to access the second page regularly. I need the "sendData" routine in MainActivity to have access to the stored values for processing.
At this time, pressing the Send button on the MainActivity page results in:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.kke.android.opener.MainActivity.sendData(MainActivity.java:47)
at com.kke.android.opener.MainActivity.onClick(MainActivity.java:30)
Which I take to mean that the the variable values are not available to the sendData routine on that page.
MainActivity
package com.kke.android.opener;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnsend = (Button) findViewById(R.id.buttonSend);
Button btnset = (Button) findViewById(R.id.buttonSet);
btnsend.setOnClickListener(this);
btnset.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
sendData(v);
break;
case R.id.buttonSet:
editParams(view);
break;
}
}
public void sendData(View view) {
Context context = getApplicationContext();
/**Load global variable from Main2Activity*/
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
//EditText editText = (EditText) findViewById(R.id.editTextIP);
//String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
//editText = (EditText) findViewById(R.id.editTextPort);
//String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
// editText = (EditText) findViewById(R.id.editTextData);
//String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
/** Called when the user taps the Set Params button */
public void editParams(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
Main2Activity
package com.kke.android.opener.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.kke.android.opener.R;
public class Main2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Restore preferences
SharedPreferences settings = getPreferences(0);
ToggleButton toggleButton = ((ToggleButton) findViewById(R.id.toggleButton));
boolean checked = settings.getBoolean("toggleChecked", false);
toggleButton.setChecked(checked);
toggleButton.setVisibility(View.GONE);
EditText editText = (EditText) findViewById(R.id.editTextIP);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("host", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextPort);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("port", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextData);
editText.setText(settings.getString("dataText", ""), TextView.BufferType.EDITABLE);
/** Set up global variable to pass to MainActivity */
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
intent.putExtra("host", "host");
intent.putExtra("port", "port");
intent.putExtra("dataText", "dataText");
startActivity(intent);
}
#Override
public void onPause() {
super.onPause();
// Get current values
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("host", host);
editor.putString("port", port);
editor.putString("dataText", dataText);
editor.putBoolean("toggleChecked", ((ToggleButton) findViewById(R.id.toggleButton)).isChecked());
// Commit the edits!
editor.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_send:
this.sendData(null);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendData(View view) {
Context context = getApplicationContext();
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text/Hex required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
EditText editTextIp = (EditText) findViewById(R.id.editTextIP);
EditText editTextPort = (EditText) findViewById(R.id.editTextPort);
if (on) {
editTextIp.setInputType(InputType.TYPE_CLASS_TEXT);
editTextPort.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
editTextIp.setInputType(InputType.TYPE_CLASS_PHONE);
editTextPort.setInputType(InputType.TYPE_CLASS_PHONE);
}
}
}
All suggestions will be appreciated.
Please remember I am very new to this.
Both of your Activities have the exact same layouts... That is probably confusing...
Anyways, you called getIntent().getExtras() when there was no extras to get (that activity just started).
Sample of your code
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
You can simply do this
Bundle extras = getIntent().getExtras();
// TODO: declare some variables here
String host, port, text;
if (extras != null) {
// TODO: assign your variables here
String host = extras.getString("host");
String port = extras.getString("port");
String dataText = extras.getString("dataText");
}
However, don't be surprised if you don't get anything because the intent could still be empty
What is happening is that your MainActivity is probably launched from the Android launcher and not from MainActivity2.
Basically when you click send, you inspect the intent that brought you here (to this activity). Since you came from the launcher, this intent does not have the data that you need to execute the function. Remember that you are setting the data for this intent in your MainActivity2 (on your oncreate method, which is kind of a bad practice in this context).
To fix this, go to the manifest and make your MainActivity2 your launcher activity:
<activity android:name="<YOUR_ACTIVITY_TWO_NAME">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This will make sure that your Activity2 will be called first, this linking to MainActivity and sending an intent with actual data.
I am trying to have messages pop up if the user does not enter their username and password, however my problem is the getApplicationcontext(), it says "cannot resolve method". how do i fix it?-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.example.rojean.prelim_project;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
Button loginBtn;
EditText txtUsername, txtPassword;
AccountsManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Object getApplication;
session = new AccountsManagement(getApplicationcontext());
txtUsername = (EditText) findViewById(R.id.nameField);
txtPassword = (EditText) findViewById(R.id.passwordField);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
loginBtn = (Button)findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
//Validation method
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with static data
// username = admin
// password = admin
if(username.equals("admin") && password.equals("admin")){
// Creating user login session
// Statically storing name="Android Example"
// and email="androidexample84#gmail.com"
session.createUserLoginSession("Android Example",
"androidexample84#gmail.com");
// Starting MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Try LoginActivity.this instead of getApplicationContext()
Use this instead of getApplicationContext():
Toast.makeText(this, "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show;
In this way you get the activity's context.
Do not use getApplicationContext(). The best way to get the Activity context is to use LoginActivity.this, where this refers to the context itself.
I'm trying to develop an app which will scan a barcode, store the value in a variable, then scan another barcode and match that value with the previous value and return a 'match' or 'no match' result. I have already got the first part working thanks to help from foamyguy, here's the initial code that I used,
package com.barcodesample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class BarcodeSample extends Activity {
private Button scanBtn;
private TextView resultsTxt;
/** Called when the activity is first created. */;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scanBtn = (Button) findViewById(R.id.scanBtn);
resultsTxt = (TextView) findViewById(R.id.resultsTxt);
scanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
resultsTxt.setText("Scanning...");
Intent intent = new intent("com.google.zxing.client.android.SCAN");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
new AlertDialog.Builder(v.getContext())
.setTitle("WARNING:")
.setMessage("You don't have Barcode Scanner installed. Please install it.")
.setCancelable(false)
.setNeutralButton("Install it now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
})
.show();
}
}
});
}
/*Here is where we come back after the Barcode Scanner is done*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel. If the user presses 'back' before a code is scanned.
resultsTxt.setText("Canceled");
}
}
}
}
Now how do I start another intent with another scan button similar to the one above, and finally how to compare both values and return the match or no match in a new screen?
Thanks in advance for the valuable advice
Use the same code on the other button except following.
startActivityForResult(intent, 1); // right now it's 0 for button 1
Now add one more section in onActivityResult for returning results for 2nd button.
if (requestCode == 1) {
// your code here that will be used for comparing.
}
Sending out SMS messages from my Android phone in Java, how can I do them one at a time?
I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?
I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:
import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import android.widget.Button;
import java.io.*;
import android.util.LogPrinter;
import java.io.*;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class JSSMS extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
.show();
String message = "Hello This Is John, Please save my new number";
String number;
try {
BufferedReader buffreader = new BufferedReader(
new FileReader(Environment
.getExternalStorageDirectory().toString()
+ "/numbers.txt"));
int i = 0;
while ((number = buffreader.readLine()) != null) {
Toast.makeText(JSSMS.this, "Sending text to:" + number,
Toast.LENGTH_SHORT).show();
sendSMS(number, message);
}
buffreader.close();
} catch (java.io.FileNotFoundException e) {
Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
.show();
}
Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
}
});
}
// ---Sends an SMS message to another device.---
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
// ---When the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
// ---When the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
}
Here's a general hint to set you in the right direction. When you have a queue of items you want to process in some asynchronous manner, one approach is use the callback/event handler/call-it-what-you-will to trigger the processing of the next element in the queue.
set up your queue of messages
have a method, e.g. 'sendNextMessage' which pops the top message off the queue and sends it
now, in your onReceive method, you can call your sendNextMessage to trigger sending the next one in the queue
For this approach to work, you need to ensure you are guaranteed to get some kind callback regardless of success or failure.
Look at the sendSms() method in this class.
When you call sendTextMessage(), you can pass a "sent" and a "delivered" intent. Target these intents back to your own application. You can have a callback so to speak when the SMS is sent or delivered.
If you look at the AndroidManifest.xml file in that same project as the references source file, you can see there are two receivers defined that register for "sms_sent" (and "sms_received") intents. If you look at the method I mentioned, you can see that before calling sendTextMessage() it creates two intents with the action "sms_sent" and "sms_delivered". This is how you get notified when an SMS is done sending.
First thing first there are four to five steps
Step 1 open button click or any trigger u start sms sending
Step 2 create Pending Intent to be broadcasted with the intent object and OFCOURSE WITH MULTIPLE PENDING INTENT... for multiple sms sending capability...
Step 3 the registered broadcast receiver will receive the pending intent
Step 4 based on the result and the received INTENT, I REPEAT THE INTENT object u send the next message ... here is a code for it
i trust it's readable enough... stay awesome
public class SMSDoer extends Activity {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI, deliveredPI;
BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onResume() {
super.onResume();
//---create the BroadcastReceiver when the SMS is sent---
smsSentReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “SMS Gone With the wind”,
//db.query update database for recurrisive message calling
//using intent object for specific message
sendSMS(“db.phoneNumber", "db.msg");
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), “Generic failure”,
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), “No service”,
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), “Null PDU”,
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), “Radio off”,
Toast.LENGTH_SHORT).show();
break;
}
}
};
//---create the BroadcastReceiver when the SMS is delivered---
smsDeliveredReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “SMS delivered”,
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), “SMS not delivered”,
Toast.LENGTH_SHORT).show();
break;
}
}
};
//---register the two BroadcastReceivers---
registerReceiver(smsDeliveredReceiver, new IntentFilter(DELIVERED));
registerReceiver(smsSentReceiver, new IntentFilter(SENT));
}
#Override
public void onPause() {
super.onPause();
//---unregister the two BroadcastReceivers---
unregisterReceiver(smsSentReceiver);
unregisterReceiver(smsDeliveredReceiver);
}
public void SmsMaker(View v) {
//query database
sendSMS(“db.phoneNumber", "db.msg", db.row);
}
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message, int rowId)
{
//create multiple Pending intent
sentPI = PendingIntent.getBroadcast(this,rowId, new Intent(SENT), 0);
deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, "+29170000017", message, sentPI,deliveredPI);
}
}