Java: Problem in accessing value of global variable - java

Please go through the code below.
String[] Info contains 2 values like this:
shiftDirection & 1 or
currGear & 5 and similar pairs.
If I receive shiftDirection & 0, I should display the previously received value of currGear.
So I create PresentGear as a global variable and when currGearis received, I store it's value in PresentGear.
Then when I receive shiftDirection & 0, I try to display PresentGear but nothing gets displayed.
PresentGear is assigned no value. It would be very helpful if someone could suggest why this is happening or if my approach is wrong, kindly suggest an alternative way.
Cheers,
Madhu
public class Images extends Activity {
/** Called when the activity is first created. */
//LinearLayout mLinearLayout;
//ImageView showImage;
String PresentGear = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
String[] Info = extras.getStringArray("MsgInfo");
Log.d("TCP","in DA Images. Message name: " + Info[0] + ", value: " + Info[1]);
if (Info[0].equals("currGear")) {
PresentGear = Info[1];
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
text_bottom.setText(Info[1]);
}
Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
DataAction(Info[0], Info[1]);
}
public void DataAction (String mName, String mVal) {
String _mName = mName;
String _mVal = mVal;
if (_mName.equals("shiftDirection") && _mVal.equals("1")) {
setContentView(R.layout.image);
//TextView text_top = (TextView) findViewById(R.id.textView1);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_up);
} else if (_mName.equals("shiftDirection") && _mVal.equals("-1")) {
setContentView(R.layout.image);
//TextView text_bottom = (TextView) findViewById(R.id.textView2);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
//text_bottom.setText(Info[1]);
showImage.setImageResource(R.drawable.shift_down);
} else if (_mName.equals("recomGear") && _mVal != null) {
Integer msgValue = Integer.parseInt(_mVal);
Integer CurrentGear = (msgValue) - 1;
Log.d("TCP","in DA Images. Current gear: " + CurrentGear);
String Gear = Integer.toString(CurrentGear);
setContentView(R.layout.image);
TextView text_top = (TextView) findViewById(R.id.textView1);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
ImageView showImage = (ImageView) findViewById(R.id.imageView1);
showImage.setImageResource(R.drawable.shift_up);
text_bottom.setText(Gear);
text_top.setText(_mVal);
//} //else if (_mName.equals("currGear") && _mVal != null) {
//PresentGear = _mVal;
//Log.d("TCP","in DA Images. Present gear1: " + PresentGear);
//setContentView(R.layout.image);
//TextView text_bottom = (TextView) findViewById(R.id.textView2);
//text_bottom.setText(_mVal);
} else if (_mName.equals("shiftDirection") && _mVal.equals("0")) {
Log.d("TCP","in DA Images. Present gear: " + PresentGear);
setContentView(R.layout.image);
TextView text_bottom = (TextView) findViewById(R.id.textView2);
TextView text_top = (TextView) findViewById(R.id.textView1);
text_top.setText("Go on");
text_bottom.setText(PresentGear);
}
}
}
Update:
Thank you all for the response. I will post the part where I am getting the string array from. It may not be the best designed code. Would be happy if any changes are suggested.
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String data[] = new String[2];
public String PGear;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
//TcpServiceHandler handler=new TcpServiceHandler(this);
//handler.execute("192.168.62.23");
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
Log.d("TCP", "Std parser " + source);
//mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
data[0] = msgName;
data[1] = tmpVal;
Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
actionOnData(data[0], data[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
return data;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
//Function to display driver messages/images based on individual messages
public void actionOnData(String name, String value) {
String tempName = name;
String tempVal = value;
if(tempName.equals("shiftDirection") && tempVal.equals("1")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("recomGear")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Drive like a man");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("shiftDirection") && tempVal.equals("-1")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else if(tempName.equals("currGear")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
PGear = data[1];
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
//finish();
} else if(tempName.equals("shiftDirection") && tempVal.equals("0")) {
Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
//mTitle.setText("Change to next higher gear");
data[1] = PGear;
Intent myIntent = new Intent();
myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
myIntent.putExtra("MsgInfo", data); // key/value pair, where key needs current package prefix.
startActivity(myIntent);
finish();
} else mTitle.setText("Just show something");
//Log.d("TCP", "Just show an image");
//}
}
}
In fact, in the above code, I have temporarily solved the issue of storing value of currGear and using it in shiftDirection, 0.

The value of PresentGear will only persist for the lifetime of your Activity. If the OS kills your Activity then the value will be lost. You should put some logging in onPause(), onStop() and onDestroy() and check how the lifecycle of your app is working. You may have to write out the value of PresentGear to SharedPreferences in onPause() and read the result in your onCreate(). Check out this link for the lifecycle:
Application fundamentals

Sounds like you should step through this code in the debugger and examine what values are being delivered to this activity. How are you constructing the Intent that gets delivered? (I suspect that either Info[0] isn't "currGear" or Info[1] is "", but something else could be going on.)

Related

Passing Data between activities Forces Close

I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");

Can ListView host TextView items that are also displayed in a separate TextView

I'm having a problem changing a TextView to a ListView. Originally, the app had a button that when clicked, runs tests to a bluetooth device and displays the results in a textview. I modified the app to contain two textviews that have the last text results and a separate xml file (connected with viewflipper) to go to a second textview that contains all of the test results, until the user clears the textview by clicking a button. I followed along with this example and checked what I was entering in the ArrayAdapter section of the code, and it appears to be what is required according to the developer's guide, but I still get his error:
Cannot resolve constructor 'ArrayAdapter(com.example.android.stardustscanner.ScannerFragment, int, int, java.lang.String)'
Why am I getting this error?
My .java file that I am making all the changes in is very long and contains a lot of thins that aren't relevant to this question and doesn't fit in the question box, so I'll try to only include the relevant parts. The error is towards the bottom with this line:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
ScannerFragment.java
public class ScannerFragment extends Fragment implements LocationListener {
ListView mListView;
//page switching things KG 8/24/17
private ViewFlipper mViewFlipper;
private float lastX;
private Button mViewLog;
private Button mReturnFlipper;
private TextView mShowData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.flipper_holder, container, false);//kg 8/24/17
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SP = PreferenceManager.getDefaultSharedPreferences(getContext());
mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlip); //KG 8/24/17
mViewLog = (Button) view.findViewById(R.id.viewLog); //kg 8/24/17
mReturnFlipper = (Button) view.findViewById(R.id.flipperReturn); //kg 8/24/17
mShowData = (TextView) view.findViewById(R.id.textView) ; //kg 8/25/2017
mShowData.setText(readFromFile()); // kg 8/25/2017
mPowerOffButton = (Button) view.findViewById(R.id.button_poweroff);
mDisconnectButton = (Button) view.findViewById(R.id.button_disconnect);
mConnectButton = (Button) view.findViewById(R.id.button_connect);
mPresence = (Button) view.findViewById(R.id.button_present);
mBattery = (ProgressBar) view.findViewById(R.id.progressBar);
mBlinkConnect = (Button) view.findViewById(R.id.button_connectionblink);
mBlinkData = (Button) view.findViewById(R.id.button_communication);
mClearLog = (Button) view.findViewById(R.id.button_clear_log);
mDeviceName = (Button) view.findViewById(R.id.button_devicename);
mDeviceSN = (Button) view.findViewById(R.id.button_devicesn);
mBatteryPerc = (TextView) view.findViewById(R.id.label_batterypct);
mListView = (ListView) view.findViewById(R.id.scanLogView); //kg 8/28/17
// mReadingLog = (TextView) view.findViewById(R.id.scanLogView);
mReadingLog.setMovementMethod(new ScrollingMovementMethod());
mReadingLog.setText(readFromFile());
telephonyManager = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
initLocationService(this.getContext());
final ActionBar actionBar = getActivity().getActionBar();
if (null == actionBar) {
return;
}
final Drawable D = getResources().getDrawable(R.drawable.stardust2);
actionBar.setBackgroundDrawable(D);
actionBar.setTitle("");
//KG 8/24/17
mViewLog.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showNext();
}
});
mReturnFlipper.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showPrevious();
}
});
}
private void setupScanner() {
Log.d(TAG, "setupScanner()");
// Initialize the send button with a listener that for click events
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isIris) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
} else {
publishMessage(Constants.COMMAND_POWEROFF);
}
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mDisconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_DISCONNECT);
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_ON_CONNECT);
}
});
mClearLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
mReadingLog.setText("");
if(SP.getBoolean("writeToFile", true)) {
writeToFile("", "", false);
}
}
});
// Initialize the ScannerService to perform bluetooth connections
mScannerService = new ScannerService(getActivity(), mHandler);
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
publishMessage(message);
}
return true;
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ScannerService.STATE_CONNECTED:
setStatus(mConnectedDeviceName);
if(mConnectedDeviceName.substring(0, 4).toLowerCase().equals("iris") || mConnectedDeviceName.substring(0, 8).toLowerCase().equals("stardust")) {
isIris = true;
mPresence.setClickable(true);
mPresence.setText("Click to detect taggant");
mPresence.setBackgroundColor(Color.parseColor("#0061ff"));
mPresence.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readoutStarted = true;
publishMessage(Constants.COMMAND_RUN_IRIS);
}
});
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
mScannerService.stop();
}
});
} else {
isIris = false;
}
if(!isIris) {
mPresence.setClickable(false);
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
publishMessage(Constants.COMMAND_ON_CONNECT);
timer = new Timer();
timerStarted = true;
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
publishMessage(Constants.COMMAND_READDATA);
}
}, 1000, 1000);
} else {
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
}
mBlinkConnect.setBackgroundColor(Color.parseColor("#11D901"));
break;
case ScannerService.STATE_CONNECTING:
setStatus("C");
break;
case ScannerService.STATE_LISTEN:
case ScannerService.STATE_NONE:
mBlinkConnect.setBackgroundColor(Color.parseColor("#ff2b0f"));
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
setStatus("D");
break;
}
break;
case Constants.MESSAGE_WRITE:
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
break;
case Constants.MESSAGE_READ:
mBlinkData.setBackgroundColor(Color.parseColor("#0091FA"));
String readMessage = (String)msg.obj;
if(isIris) {
readIris(readMessage);
} else {
readNormal(readMessage);
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
setupScanner();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
/*case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}*/
case R.id.settings_button: {
Intent serverIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(serverIntent, REQUEST_SHOW_SETTINGS);
return true;
}
}
return false;
}
/**
*
* #param data String
* #param append boolean
*/
private void writeToFile(String data, String uploadData, boolean append) {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
String fname2 = "starDust.csv";
File file = new File (myDir, fname);
File file2 = new File (myDir, fname2);
//if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file, append);
out.write(data.getBytes(), 0, data.getBytes().length);
out.flush();
out.close();
FileOutputStream out2 = new FileOutputStream(file2, append);
out2.write(uploadData.getBytes(), 0, uploadData.getBytes().length);
out2.flush();
out2.close();
if(mConnectedDeviceName != null) {
Log.d(TAG, "Connecting " + SP.getString("server_ip", "") + SP.getString("server_username", "") + SP.getString("server_password", ""));
new FTPUploadTask().execute(mConnectedDeviceName, SP.getString("server_ip", ""), SP.getString("server_username", "") , SP.getString("server_password", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
private String readFromFile() {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
File file = new File (myDir, fname);
StringBuilder text = new StringBuilder();
if (file.exists ()) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.insert(0, line + System.getProperty("line.separator"));
}
br.close();
} catch (Exception e) {
}
}
return text.toString();
}
private void readNormal(String readMessage) {
String parsedData[];
if(readMessage.contains(";")) {
if(readMessage.equals(";")) {
parsedData = bufferedMessage.trim().split(",");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.split(";");
bufferedMessage += partialMessage[0];
parsedData = bufferedMessage.trim().split(",");
if (partialMessage.length > 1) {
bufferedMessage = partialMessage[1];
} else {
bufferedMessage = "";
}
}
} else {
bufferedMessage += readMessage.trim();
return;
}
if(parsedData.length == RESPONSE_SIZE && parsedData[0].equals("U")) {
if(parsedData[1].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[1]) > maxU1 || hitTrigger) {
maxU1 = Integer.parseInt(parsedData[1]);
}
}
if(parsedData[2].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[2]) > maxU2 || hitTrigger) {
maxU2 = Integer.parseInt(parsedData[2]);
}
}
if(parsedData[3].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[3]) > maxU3 || hitTrigger) {
maxU3 = Integer.parseInt(parsedData[3]);
}
}
double u1val = Double.parseDouble(parsedData[1]);
double u2val = Double.parseDouble(parsedData[2]);
double u1u2div = 0;
if(u2val > 0) {
u1u2div = ((u1val / u2val) * KFactor);
}
if(parsedData[4].matches("[-+]?\\d*\\.?\\d+")) {
mBatteryPerc.setText(parsedData[4] + "%");
mBattery.setProgress(Integer.parseInt(parsedData[4]));
}
}
taggantType = 0;
if(maxU1 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 4;
} else {
taggantType += 0;
}
if(maxU2 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 2;
} else {
taggantType += 0;
}
if(maxU3 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 1;
} else {
taggantType += 0;
}
Log.d(TAG, Integer.toString(taggantType));
Log.d(TAG, Boolean.toString(hitTrigger));
Log.d(TAG, bufferedMessage);
// Check if hit threshold, if so hitTrigger is enabled.
if(taggantType > 0) {
savedTaggantType = taggantType;
hitTrigger = true;
mPresence.setText("VALID TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#11D901"));
} else if(taggantType == 0 && hitTrigger) {
hitTrigger = false;
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Taggan Type: N" + Integer.toString(savedTaggantType) +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"N" + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
maxU1 = 0;
maxU2 = 0;
maxU3 = 0;
savedTaggantType = 0;
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
/**
* #param readMessage String
*/
public void readIris(String readMessage) {
if(!readoutStarted) {
return;
}
String parsedData[];
if(readMessage.contains(";")) {
readoutStarted = false;
if(readMessage.equals(";")) {
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
bufferedMessage += partialMessage[0].trim();
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
}
} else {
bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
return;
}
Log.d(TAG, Arrays.toString(parsedData));
boolean passed = false;
int v1 = 0;
int v2 = 0;
if(parsedData[3].equals("S")) {
passed = true;
String values[] = parsedData[7].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
} else {
Log.d(TAG, Arrays.toString(parsedData));
String values[] = parsedData[5].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"Valid:" + (passed ? "YES" : "NO") +
System.getProperty("line.separator") +
"Values: " + "T" + v1 + " / " + v2 +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
mListView.setAdapter(arrayAdapter);
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
I have three xml files associated with this problem, but because of space I'll only include the one that contains the ListView and remove the other buttons.
view_list.xml contains the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/viewList"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/listview_holder"
android:layout_alignParentTop="true"
android:layout_alignTop="#id/button_holder"
android:layout_weight=".1"
android:layout_height="wrap_content">
<ListView
android:id="#+id/scanLogView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:maxLines="4096"
android:scrollbars="vertical"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The error was with ArrayAdapter. I changed the decloration from
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, listItems);
It now builds the project and displays the listview.

Android send email with attachment error

I want to send email with an attachment from my app (attachment is csv file), but Gmail says, that attachment couldn't be added. Is mistake in converting text into csv or in Adding attachment to gmail?
My code:
public class EmailInput extends DialogFragment {
View mainView;
TextView email;
Button submitSend;
ArrayList<String> resultsEmail;
ArrayList<String> valuesMail;
TextView soucetVysledkuMail;
String subject = "Kubírovací kalkulačka";
MainActivity MA;
String attachmentFile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MA = (MainActivity) getActivity();
mainView = inflater.inflate(R.layout.fragment_email_input, container, false);
email = (TextView) mainView.findViewById(R.id.email);
submitSend = (Button) mainView.findViewById(R.id.submitSend);
resultsEmail = ((MainActivity) getActivity()).getVysledky();
valuesMail = ((MainActivity) getActivity()).getValues();
soucetVysledkuMail = ((MainActivity) getActivity()).getSoucetVysledku();
getDialog().setTitle("Odeslat výsledky");
submitSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String FILENAME = "email-attachment.csv";
String string = "";
try {
FileOutputStream fOut = ((MainActivity) getActivity()).getContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
for (int i = 0; i < resultsEmail.size(); i++) {
string += resultsEmail.get(i) + "," + valuesMail.get(i);
}
string += "Součet výsledků:," + MA.getsoucetVsechVysledkuMA();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
attachmentFile = "mail-attachment.csv";
Uri URI = Uri.parse("file://" + attachmentFile);
String content = results();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email.getText().toString()});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, content);
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Vyberte aplikaci:"));
}
});
return mainView;
}
public String results() {
String content = "";
for (int i = 0; i < resultsEmail.size(); i++) {
int cislovka = i+1;
content += cislovka + ". " + resultsEmail.get(i) + " (" + valuesMail.get(i) + ") \n";
}
content += "Součet výsledků: " + MA.getsoucetVsechVysledkuMA();
return content;
}
}
There is a problem with permissions. If you want to attach file to your mail, it has to be saved in a public folder like Documents.

What could cause an Android activity to loop infinitely?

I am writing a simple application to scan and record WiFi Access Points, there are three options; a single scan, 10 scans, or scan for a period of time.
When I enter my nWiFiScans activity it preforms the scans, records the file and STARTS THE ACTIVITY AGAIN!!!
WHY WOULD IT DO THIS???
nWiFiScans.java
public class nWiFiScans extends Activity
{
//declarations
public static String pntNameStr;
public static int numScans;
public static int scansMin;
LinearLayout layout1;
ScrollView scrollLayout;
TextView label1;
EditText n1Text;
EditText n2Text;
LayoutParams params_layout1;
WifiManager mainWifi = null;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
Intent intent;
SimpleDateFormat time;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
scrollLayout = new ScrollView(this);
scrollLayout.setBackgroundColor(Color.BLUE);
//Create new layout in "this" activity
params_layout1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, 1);
layout1 = new LinearLayout(this);
layout1.setBackgroundColor(Color.RED);
layout1.setLayoutParams(params_layout1);
//Create TextView in "this" activity
label1 = new TextView(this);
label1.setBackgroundColor(Color.YELLOW);
//Put some text in the TextView
// Get the message from the intent
intent = getIntent();
pntNameStr = intent.getStringExtra(MainActivity.EXTRA_pntNameStr);
numScans = intent.getIntExtra(MainActivity.EXTRA_numScans, 1);
label1.setText(pntNameStr);
//Place the TextView inside the Layout
layout1.addView(label1);
layout1.setOrientation(LinearLayout.VERTICAL);
//scrollLayout.addView(label1);
//layout1.addView(n1Text);
//layout1.addView(n2Text);
//By default the layout is set to HOR, so we change it to VERT orientation:
// Display layout1 when the activity is created:
setContentView(layout1);
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
checkIfWifiIsOn(mainWifi);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
label1.setText("Starting Scan..."+String.valueOf(numScans));
}
public void checkIfWifiIsOn(WifiManager mainWifi)
{
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
else {Toast.makeText(getApplicationContext(), "wifi is enabled... thats good...",
Toast.LENGTH_SHORT).show();}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
File root = null;
try
{
root = new File(Environment.getExternalStoragePublicDirectory("SurveyAppData"), "ScanResults");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "IM MOTHERFUCKING DONE" ,
Toast.LENGTH_SHORT).show();
//Log.d("Scan Results",sb.toString());
Intent i=new Intent(nWiFiScans.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
catch(IOException e)
{
e.printStackTrace();
Toast.makeText(this, "!!! - Could NOT Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
}
}
public class WifiReceiver extends BroadcastReceiver
{
// This method call when number of wifi connections changed
long fisrtScanTS;
private String FILENAME = pntNameStr;
public FileOutputStream outputStream;
#SuppressLint("NewApi")
public void onReceive(Context c, Intent intent)
{
time = new SimpleDateFormat("ddMMyyyyhhmmss");
int ScanTime = numScans;
if(ScanTime==1 | ScanTime==10)
{
for (int scanNum = 1; scanNum<ScanTime+1; scanNum++)
{
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do
{
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}
} while(fisrtScanTS == (wifiList.get(1)).timestamp);
Toast.makeText(getApplicationContext(), "Scan number " + scanNum ,
Toast.LENGTH_SHORT).show();
}
}else if (ScanTime!=0)
{
Calendar timeNow = Calendar.getInstance();
Calendar timeEnd = Calendar.getInstance();
timeEnd.set(timeNow.YEAR, timeNow.MONTH, timeNow.DAY_OF_MONTH, timeNow.HOUR, timeNow.MINUTE+numScans, timeNow.SECOND);
while(!(timeNow.after(timeEnd))){
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do {
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}} while(fisrtScanTS == (wifiList.get(1)).timestamp);
timeNow = Calendar.getInstance();
Toast.makeText(getApplicationContext(), timeNow.getTime().toString() + " :: " + timeEnd.getTime().toString() ,
Toast.LENGTH_SHORT).show();
}
}
generateNoteOnSD(FILENAME, sb.toString());
FILENAME="x";
ScanTime=0;
}
}
}
MainActivity.java
public class MainActivity extends Activity
{
LinearLayout mainLayout,leftLayout,rightLayout;
EditText pointName;
EditText scanTime;
Button scan10, scan1, timedScan;
TextView msg;
LayoutParams paramsL,paramsR;
static final String EXTRA_pntNameStr = "com.example.surveyappv2.pntNameStr";
static final String EXTRA_scanTimeMin = "com.example.surveyappv2.scanTimeMin";
static final String EXTRA_numScans = "com.example.surveyappv2.numScans";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
paramsL = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
paramsR = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
leftLayout = new LinearLayout(this);
leftLayout.setOrientation(LinearLayout.VERTICAL);
leftLayout.setLayoutParams(paramsL);
leftLayout.setGravity(Gravity.CENTER_HORIZONTAL);
leftLayout.setBackgroundColor(Color.YELLOW);
rightLayout = new LinearLayout(this);
rightLayout.setOrientation(LinearLayout.VERTICAL);
rightLayout.setLayoutParams(paramsR);
rightLayout.setGravity(Gravity.CENTER_HORIZONTAL);
rightLayout.setBackgroundColor(Color.BLUE);
scanTime = new EditText(this);
scanTime.setHint("Scan Duration (min)");
scanTime.setInputType(InputType.TYPE_CLASS_NUMBER);
pointName = new EditText(this);
pointName.setHint("Enter Point Name");
scan10 = new Button(this);
scan1 = new Button(this);
timedScan = new Button(this);
msg = new TextView(this);
scan10.setText("Do 10 Scans");
scan1.setText("Do a Single Scan");
timedScan.setText("Timed Scan");
msg.setText("Alec Sucks");
leftLayout.addView(pointName);
leftLayout.addView(scanTime);
rightLayout.addView(msg);
rightLayout.addView(scan10);
rightLayout.addView(scan1);
rightLayout.addView(timedScan);
mainLayout.addView(leftLayout);
mainLayout.addView(rightLayout);
mainLayout.setBackgroundColor(Color.RED);
setContentView(mainLayout);
setButtonClickListener();
}
private void setButtonClickListener()
{
scan10.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan10.getText();
msg.setText(message2);
startScan(mainLayout,10);
}
});
scan1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan1.toString();
msg.setText(message2);
startScan(mainLayout,1);
}
});
timedScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + timedScan.toString();
msg.setText(message2);
startScan(mainLayout,Integer.parseInt(scanTime.getText().toString()));
}
});
}
#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;
}
public void startScan(View view, int numScans)
{
Intent intent = new Intent(this, nWiFiScans.class);
String pntNameStr = pointName.getText().toString();
intent.putExtra(EXTRA_pntNameStr, pntNameStr);
intent.putExtra(EXTRA_numScans, numScans);
startActivity(intent);
}
}
I ran it, removed the file creation and the Intent(You only need to call finish();) and then it worked. Have you checked that it actually goes through File creation for you? Because mine got stuck there and then it jumps out of try so it can't reach the finish(); call, I also called unregisterReceiver(receiverWifi); before finish();
EDIT, File creation:
File sdCard = Environment.getExternalStorageDirectory(); //returns sdcard directory
File dir = new File (sdCard.getAbsolutePath() + "/mydirectory");
dir.mkdirs();
File file = new File(dir, "filename");

Sending Data From Form to be Displayed in Another View Android

I'm trying to display text that is input by the user if it is not null but I'm having some trouble (I'm a Java noob). Here is the flow of my app:
Starts at Main.java with a button:
-Button: Profile
If you click profile, the app goes to the profile page Display.java that also has a button:
-Button: Edit Profile
-This view also displays the information (name, phone number, zip code, etc)
When a user clicks Edit Profile, the program goes to a form at EditProfile.java, which has a form where users enter the information and then there is a button to submit.
-Button: Submit
This submit button takes the user back to the previous view (Display.java) and displays the information that was previously entered in the form with the string resultText.
I'm not sure how to make this work. If anyone has any suggestions, I'd really appreciate the help!
Edit: One thing to note is that I'm getting a "Dead Code" error on the if expression in Display.java
Display.java:
public class Display extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
String newline = System.getProperty("line.separator");
TextView resultText = (TextView) findViewById(R.id.resultText);
Bundle bundle = getIntent().getExtras();
String firstName = null;
String lastName;
String phoneNumber;
String city;
String zipCode;
if(firstName != null) {
firstName = bundle.getString("EditTextFirstName");
lastName = bundle.getString("EditTextLastName");
phoneNumber = bundle.getString("EditTextPhoneNumber");
city = bundle.getString("EditTextCity");
zipCode = bundle.getString("EditTextZipCode");
resultText.setText("Name: " + firstName + " " + lastName + newline + "Phone Number: " + phoneNumber +
newline + "City: " + city + newline + "Zip Code: " + zipCode + newline);
}
Button profile = (Button) findViewById(R.id.button1);
profile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Display.this, EditProfile.class));
}
});
}
}
EditProfile.java:
public class EditProfile extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
}
public void sendFeedback(View button) {
final EditText firstnameField = (EditText)this.findViewById(R.id.EditTextFirstName);
String firstname = firstnameField.getText().toString();
final EditText lastnameField = (EditText) findViewById(R.id.EditTextLastName);
String lastname = lastnameField.getText().toString();
final EditText phoneNumberField = (EditText) findViewById(R.id.EditTextPhoneNumber);
String phoneNumber = phoneNumberField.getText().toString();
final EditText cityField = (EditText) findViewById(R.id.EditTextCity);
String city = cityField.getText().toString();
final EditText zipCodeField = (EditText) findViewById(R.id.EditTextZipCode);
String zipcode = zipCodeField.getText().toString();
int count = 0;
int fnlen=firstname.length();
int lnlen=lastname.length();
int phlen=phoneNumber.length();
int citylen=city.length();
int zclen=zipcode.length();
if (fnlen<=0){
firstnameField.setError("Enter your first name");
}
else {
count += 1;
}
if (lnlen<=0){
lastnameField.setError("Enter your last name");
}
else {
count += 1;
}
if (phlen<=0){
phoneNumberField.setError("Enter your ten digit phone number");
}
else if (phlen!=10){
phoneNumberField.setError("Phone number must be ten digits");
}
else {
count += 1;
}
if (citylen<=0){
cityField.setError("Enter your city");
}
else {
count += 1;
}
if (zclen<=0){
zipCodeField.setError("Enter your Zip Code");
}
else if (zclen!=5){
zipCodeField.setError("Enter a five digit zip code");
}
else {
count += 1;
}
if (count == 5) {
Intent intent = new Intent();
intent.setClass(this,Display.class);
intent.putExtra("EditTextFirstName",firstnameField.getText().toString());
intent.putExtra("EditTextLastName",lastnameField.getText().toString());
intent.putExtra("EditTextPhoneNumber",phoneNumberField.getText().toString());
intent.putExtra("EditTextCity",cityField.getText().toString());
intent.putExtra("EditTextZipCode",zipCodeField.getText().toString());
startActivity(intent);
}
else {
count = 0;
}
}
}
try with `Intent i= getIntent();
if(i.getExtras()!=null){
firstName = bundle.getString("EditTextFirstName");
lastName = bundle.getString("EditTextLastName");
phoneNumber = bundle.getString("EditTextPhoneNumber");
city = bundle.getString("EditTextCity");
zipCode = bundle.getString("EditTextZipCode");
resultText.setText("Name: " + firstName + " " + lastName + newline + "Phone Number: " + phoneNumber +
newline + "City: " + city + newline + "Zip Code: " + zipCode + newline);
}`in your Display Class instead of firstName != null) { ...} and let me know if any queries.

Categories

Resources