How to pass data from one activity to another activity in Android - android

Im a newbie to android. i want to create an application that sends the user1 location to the user2 using ServerSocket.
public class ToMain extends Activity {
TextView info, infoip, msg;
String message ="";
ServerSocket serverSocket;
String s="",t="";
public Double b,c;
public int i;
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
ToMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readUTF();
I Split the Latitude and Longitude this way in the Server side
for(int j=0;j<i;j++){
if(messageFromClient.charAt(j)!='+' && bool==false){
s=s+messageFromClient.charAt(j);
}
else{
bool=true;
}
if(bool){
t=t+messageFromClient.charAt(j);
}
}
I Store in these two Variable
b = Double.parseDouble(s);
c = Double.parseDouble(t);
ToMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
String msgReply = "Location Sent!" + count;
dataOutputStream.writeUTF(msgReply);
i want to send those variable from here to the main activity which contain the map
// startActivity(intent);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
ToMain.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
How do i pass a and b to the main activity.

Pass data through intents.
Intent data = new Intent(this,SecondActivity.class);
data.putExtra("keyA",a);
data.putExtra("keyB",b);
startActivity(data);
In second activity in onCreate()
Intent intent = getIntent();
Double a = intent.getDoubleExtra("keyA",0);
Double b = intent.getDoubleExtra("keyB",0);

Use Intent to pass data from one activity to another activity
Intent intent = new Intent(this,SecondActivity.class);
intent .putExtra("key1",value);
intent .putExtra("key2",value);
startActivity(intent );
In second activity in onCreate()
Intent intent = getIntent();
Double a = intent.getDoubleExtra("key1",0); // Notice 0 is the default value here
Double b = intent.getDoubleExtra("key2",0);

To pass data from one Activity to another, you can use Extras in Intent.
Intent intent = new Intent("ACTIVITY_INTENT");
intent.putExtra("selection", position);
startActivity(intent);
You can send Binary, Text and multiple pieces as listed here,
http://developer.android.com/training/sharing/send.html
To receive the data in the next activity, in the oncreate method of the activity,
extras = getIntent().getExtras();
int value = extras.getInt("selection");
In case if you want to persist the data, the simplest way to achieve this would be saving it in Shared Preferences.
Developer link has good information on how to implement this - http://developer.android.com/training/basics/data-storage/shared-preferences.html
To write the data,
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
To read the data,
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
all the best

In Android user interface is displayed through an activity. Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and that can interact with each other. During activity interaction we might required to pass data from one activity to other.
Now, to pass data from one activity to other in android, you need to do the following :
You can send data from one actvity to another with an Intent.
An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra() method. Data is passed as extras and are key/value pairs. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable objects from one activity to other.
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

Related

IntentService lost work in executor

I have a classe for download files by an executor :
this.getFreshGoolgletoken(new CallBackTokenRefresh() {
#Override
public void getFreshGoogleToken(String token,String userEmail) {
ArrayList<ExecuteSynchroneRequest> mesRequetes = new ArrayList<>();
Intent mServiceIntent = new Intent(context, TraitementPermisLoaded.class);
for (CollectionPermis permis : collectionPermis){
// stocker les permis + les s3Key
int revision = permis.revision;
final String uuid = permis.uuid;
Log.i(LOG_TAG,"synchro OnLoop permis num & revision :"+uuid+"/"+revision);
Map<String,String> params = new HashMap<>();
params.put("uuid",uuid);
params.put("revision",String.valueOf(revision));
mesRequetes.add(new ExecuteSynchroneRequest(AwsEworkPermitsRoutes.PERMITS,params,context,token,apiClient,uuid,handler,mServiceIntent,callBack));
}
ExecutorService execute = Executors.newSingleThreadExecutor();
for(Runnable r : mesRequetes){
execute.execute(r);
}
execute.shutdown();
}
In this methode i have an IntentService(mServiceIntent) for handle a long treatement on my download. My executor class handle intentService like this in switch command :
case PERMITS:
if(mServiceIntent == null) break;
mServiceIntent.setData(Uri.parse(responseData));
mServiceIntent.putExtra("myHandler", new Messenger(handler));
mServiceIntent.putExtra("ptUuid", uuid);
context.startService(mServiceIntent);
break;
mServiceIntent Class is :
public class TraitementPermisLoaded extends IntentService {
static final String LOG_TAG = "ewp-executor ";
SharedPreferences sharedPreferences;
Handler handler;
public TraitementPermisLoaded() {
super("TraitementPermisLoaded");
setIntentRedelivery(true);
Log.i(LOG_TAG," service traitement permis called 2 ");
}
#Override
protected void onHandleIntent(Intent workIntent) {
this.sharedPreferences = getApplicationContext().getSharedPreferences("DATA", Context.MODE_PRIVATE);
// Gets data from the incoming Intent
String responseData = workIntent.getDataString();
Messenger messenger = null;
String ptUuid = "";
Bundle extras=workIntent.getExtras();
if (extras!=null) {
messenger=(Messenger)extras.get("myHandler");
ptUuid = extras.getString("ptUuid");
}
String permisUuid = "";
PtWrapper pt = null;
try {
ObjectMapper mapper = new ObjectMapper();
pt = mapper.readValue(responseData, PtWrapper.class);
HandleJson handleJson = HandleJson.getInstance(getApplicationContext());
permisUuid = pt.getPermisTravailFormContext().permisTravail.uuid;
if (permisUuid != null) {
handleJson.writeInInterneFileSysteme(sharedPreferences.getString("email",null),pt, permisUuid);
} else {
throw new HandleJsonNoPermisException("le UUID est null on ne peut pas enregistrer ce permis");
}
handleJson.setKpi(pt);
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("myevent", "un permis ok");
message.setData(bundle);
messenger.send(message);
} catch (IOException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
Message message = Message.obtain();
Bundle bundle= new Bundle();
bundle.putString("error", ErrorsCodes.CODE_40.toString()+" / permit uuid : "+ptUuid);
message.setData(bundle);
try {
messenger.send(message);
} catch (RemoteException e1) {
e1.printStackTrace();
Log.i(LOG_TAG,"erreur messager : "+e1.getMessage());
}
} catch (HandleJsonNoPermisException e) {
Log.i(LOG_TAG, e.getMessage());
e.printStackTrace();
} catch (RemoteException e) {
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}catch(Exception e){
Log.i(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}
I load 27 files but only 14 get a treatment, the Intentservice stop to work, it'seems to be after activity change but not sure. After loaded files, I change my activity by another, but intentService get all request in the queue. I have use IntentService because it will finish working all process before stopping?
What did I do wrong?
Thanks
the error source is the size of data in myService.setData(mydata>250ko). For all data more than 250 ko the service stop with this error message :
A/ActivityManager: Service done with onDestroy, but executeNesting=2:
ServiceRecord{5c8e958 u0
com.alit.aws.android.eworkpermit/.lib.TraitementPermisLoaded
There is another way to pass large data more than 250 k to my intentService ? I have tried :
->mServiceIntent.setData(Uri.parse(responseData));
->mServiceIntent.putExtra("myData",responseData);
I have found a solution, remove the "setData(responseData)" and replace it by a globalHasMap. After the end of treatment I remove item in hashMap.
May be it's not awesome but i have not found a better solution.
If someone can show me a better way, do it ;-)
Thanks

Camera of android becomes null when switching from third activity to second or 1st Activity

Why Surface View camera becomes null after switching from one activity to another in Android? When there were 2 classes and I was switching from 1st to 2nd Activity and from 2nd to 1st Activity, everything was working fine. But when I started a new activity, that is the third one, switching from third to any other activity makes camera null that's why the activity crashes but when clicked on "OK" the application continues. (In my code, Camera1 becomes null). What could be the reason of it? I don't want the message to appear that the activity has crashed
train.class(3rd Activity)
public void saveClicked(View v) {
save.setVisibility(View.INVISIBLE);
text.setVisibility(View.VISIBLE);
saveName.setVisibility(View.VISIBLE);
txtEditor.setVisibility(View.VISIBLE);
try {
//label++;
File Root = Environment.getExternalStorageDirectory();
LabelFile = new File(Root, "labels.txt");
roughFile= new File(Root,"rough.txt");
FileWriter Writter = new FileWriter(roughFile,false);
out = new BufferedWriter(Writter);
if(!roughFile.exists()){
roughFile.createNewFile();
Writter.write("a," +number);
}
///*-*---------------------------------------------------------------*-*//
aFile = new File(Root, "string.txt");
FileWriter aWritter = new FileWriter(aFile,true);
BufferedWriter bWritter = new BufferedWriter(aWritter);
bWritter.write(txtEditor.getText().toString()+"," +number+"\n");
bWritter.close();
///*-*---------------------------------------------------------------*-*//
FileWriter fileWritter = new FileWriter(LabelFile,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
for (int i=0;i<10;i++) {
bufferWritter.write(txtEditor.getText().toString()+"," +number+"\n");
}
MainActivity.traincount++;
number=number+1;
Writter.write("a," +number);
Writter.close();
bufferWritter.close();
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(LabelFile));
while ((line = br.readLine()) != null) {
// use comma as separator
country = line.split(cvsSplitBy);
text.setText(country[1]);
//write=true;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG).show();
MainActivity.in=false;
FdActivity.my=true;
FdActivity.counterForClick=0;
MainActivity.CounterForRecog=17;
MainActivity.counterForUnknown=11;
Intent objIntent = new Intent(getApplicationContext(), FdActivity.class);
startActivity(objIntent);
} catch (Exception e) {
}
}
FdActivity.class(1st Activity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.face_detect_surface_view);
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() { // this will send data through UI Thread, so you must update any UI Control only within this code.
#Override
public void run() {
counterForClick++;
if(counterForClick==6){
if(MainActivity.in==false) {
//my=true;
camera1.takePicture(null, null, mPicture1);
counterForClick=0;
}
}
}
});
}
}, 0, 500);
}
This is how the system manages its memory. The activity lifecycle is documented, and allows for such interruptions. So, your activity should implement onSaveInstanceState() and onRestoreInstanceState(), just carefully follow the instructions.
Working with camera in such scenario is a challenge, and I usually prefer to stick to one camera-based activity, and manage the in-app navigation via fragments.

Variables that are needed for Bluetooth Connection

Currently, I'm trying to figure out how to stay connected with a device via Bluetooth throughout Activities. I have a few variables that I initialize to get the connection going.
My previous activity flow is Main Page > User input Text page > Bluetooth Connection(SENDING INFO).
So in this way, every time I go back to the User Input Text Page, the Bluetooth connection will be reset because when I go the next page, it'll rerun all the receivers and stuffs.
Now I'm moving the Bluetooth Connection forward. Meaning now it is Main Page > Bluetooth Connection > User Input Text Page(SEND).
But after I connect on my Bluetooth Connection page, I'm not sure what variables I should bring over/save inside SharedPreferences, so that the Bluetooth connection stays and I can send right away.
//This method runs when I click a device on my ListView.
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetoothAdapter.cancelDiscovery();
System.out.println("Bluetooth Adapter2 = "
+ bluetoothAdapter.cancelDiscovery());
SiriListItem item = delist.get(arg2);
mAdapter.notifyDataSetChanged();
// When device being clicked
count++;
click = 1;
// Get the device MAC address, which is the last 17 chars in the
// View
String info = item.message;
String address = info.substring(info.length() - 17);
BlueToothAddress = address;
if (click == 1) {
clientThread ct = new clientThread();
ct.start();
}
};
};
//This is the clientThread if click == 1, it'll start this.
private class clientThread extends Thread {
public void run() {
try {
//
bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress);
socket = bdDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg2 = new Message();
msg2.obj = "Please wait, connecting to server: "
+ BlueToothAddress;
msg2.what = 0;
LinkDetectedHandler.sendMessage(msg2);
socket.connect();
Log.i("tag", "This is the pairing section");
Message msg = new Message();
msg.obj = "Device connected. Sending message is allowed.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
readThread = new readThread();
readThread.start();
click++;
} catch (IOException e) {
Message msg = new Message();
msg.obj = "Error! Can't connect to device. Please try again.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
click--;
}
}
};
public class readThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
String tmp = null;
try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
// read the data from the inputStream
if ((bytes = mmInStream.read(buffer)) > 0) {
for (int i = 0; i < bytes; i++) {
tmp = "" + buffer[i];
String st = new String(tmp);
tmp = null;
Message msg = new Message();
msg.obj = st;
msg.what = 1;
}
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}
//On Click it'll send the message stored in the editText.
buttonConnect.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View arg0) {
if (count == 0) {
Toast.makeText(bluetoothtest.this,
"Please connect to a device first.",
Toast.LENGTH_LONG).show();
}
// Need API=14
else if (!socket.isConnected()) {
Toast.makeText(bluetoothtest.this,
"Connecting! Please wait.", Toast.LENGTH_LONG)
.show();
} else {
try {
sendMessageHandle(contentRow1.getText().toString(),
contentRow2.getText().toString(), contentRow3
.getText().toString(), contentRow4
.getText().toString());
// sendMessageHandle(contentRow2.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
So the main thing is. What method should I have in my User Input Text Page? Must I have all this method in my User Input Text Page or can I just bring over variables via SharedPreferences?
Thanks.
It is probably bad practice to be handling bluetooth connections on the main thread. You should really handle the bluetooth connection/maintenance through a Service/background thread. Your activities can then talk to the service via a BroadcastReceiver and Handles.

FTDI Android - create new activity

This code is able to make the android device as a USB host for the hardware model. It also can read data from the hardware correctly in Main Activity. However, as soon as I moved it to another activity, everything still works but the data reading is incorrect.
For instance, I'm trying to write the data read into file. First activity is to input filename and just a button to send to another activity. The code below is in the second activity
public class Temp extends Activity {
private FileOutputStream outputStream;
public static D2xxManager ftD2xx= null;
Handler mHandler = new Handler();
FT_Device ftDev = null;
int devCount = 0;
UsbDevice device = null;
TextView Text =null;
String temp = null;
_4DPoint P = null;
int rd = 0;
byte[] byt = null;
byte[] Fdata = null;
String outp = "";
String From_Serial = "";
int Min = -1;
String fileName;
Context c;
final Runnable updateResults = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Text.setText("" + Min + '\n' + temp);
}
};
public void getData(){
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byt = new byte[256];//{(byte)'a','b','c','d',};
Toast.makeText(getBaseContext(), "start " + fileName , Toast.LENGTH_LONG).show();
Text = (TextView)findViewById(R.id.test2);
device = (UsbDevice) getIntent().getParcelableExtra("USB");
ftD2xx = D2xxManager.getInstance(c);
ftD2xx.addUsbDevice(device);
devCount = ftD2xx.createDeviceInfoList(c);
if (devCount > 0) {
ftDev = ftD2xx.openByUsbDevice(c, device);
}
if( ftDev.isOpen() == true ) {
ftDev.setBitMode((byte)0 , D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(38400);
ftDev.setDataCharacteristics(D2xxManager.FT_DATA_BITS_8, D2xxManager.FT_STOP_BITS_1, D2xxManager.FT_PARITY_NONE);
ftDev.setFlowControl(D2xxManager.FT_FLOW_NONE, (byte) 0x0b, (byte) 0x0d);
Thread t = new Thread() {
public void run() {
int i;
while(true){
rd=0;
while (rd==0){
rd = ftDev.read(byt, 14);
}
for(i=0; i<rd; i++)
outp += (char)byt[i];
From_Serial = new String(outp);
P = new _4DPoint(From_Serial);
temp = String.format("%s: %f %f %f %f %d\n", From_Serial, P.R, P.G, P.B, P.L, P.camera);
try {
outputStream.write(temp.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outp = "";
mHandler.post(updateResults);
}
}
};
t.start();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (D2xxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color);
// Show the Up button in the action bar.
setupActionBar();
Intent intent = getIntent();
fileName = intent.getStringExtra("File Name");
c = this;
getData();
}
The set up should be fine since it's reading data from hardware, but the data read is incorrect.
Also, I'm wondering why we need to create new thread while reading data. I tried not creating new thread and it didn't work well, but still have no idea why? I tried to contact the person who wrote the code to read data but no reply.
Any help would be really appreciated :)
You state that you receive data, therefor I think you should look at your ftDev settings. Try for example to set ftDev.setBaudRate(115200) (this worked for me) or try playing with your other ftDev Settings a little bit.
The settings I use in my programm are:
int baudRate = 115200;
byte stopBit = 1; /*1:1stop bits, 2:2 stop bits*/
byte dataBit = 8; /*8:8bit, 7: 7bit*/
byte parity = 0; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl = 1; /*0:none, 1: flow control(CTS,RTS)*/
If this won't work, it is wise to first check this data communication with a computer program e.g. or to analyse the incomming 'wrong' data.

Android: Intermitent application flow issue

I'm facing with an intermittent application flow issue.
Here, I've got a Login screen where I'm able to login for the first time. But when I'm logging out and/or re-loging in, I'm unable to traverse further. As a work around, I need to uninstall my application and reinstall it and the flow is ok.
Can anyone please guide me on the possible issue.
LoginActivity.java
GetWebServiceManager passwordExpiryWSManager = new GetWebServiceManager();
//to check network connectivity (data connection/Wi-Fi)
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInformation = connectionManager.getActiveNetworkInfo();
if (networkInformation != null && networkInformation.isConnected() == true) {
try {
// passwordExpiryString = passwordExpiryWSManager.execute("http://172.25.164.143:8088/api/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();
passwordExpiryString = passwordExpiryWSManager.execute(AppConstants.URL + "/Login/GetExpiredPassword/?lContactKey=" + username.getText().toString()).get();
jsonObjectPassExpiry = new JSONObject(passwordExpiryString);
jsonArrayPassExpiry = jsonObjectPassExpiry.getJSONArray("LstLoginDetail");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Converting JSON string response from Webservice into Java Object
* */
if (jsonArrayPassExpiry != null) {
Gson gson = new Gson();
LoginTO[] loginExpTO = gson.fromJson(jsonArrayPassExpiry.toString(), LoginTO[].class);
loginListPassExpiry = Arrays.asList(loginExpTO);
intent = getIntent();
if (loginListPassExpiry.get(0).getlSuccess() == 1) {
intent.setClass(getApplicationContext(), PortfolioSummaryFragmentActivity.class);
// intent.putExtra("sToken", loginList.get(0).getsToken());
startActivity(intent);
} else {
intent.setClass(getApplicationContext(), PasswordExpiryActivity.class);
// intent.putExtra("sToken", loginList.get(0).getsToken());
startActivity(intent);
}
} else {
Toast.makeText(getApplicationContext(), "Service is not responding. Please try again later!!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Network connection unavailable. Please check your data plan or Wi-Fi connection!!", Toast.LENGTH_SHORT).show();
}
Logout.java
public class LogoutActivity extends Activity {
private TextView successResponse;
private Intent intent;
private Button btnLLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logout_success);
successResponse = (TextView) findViewById(R.id.txtvwLSuccessMessage);
btnLLogin = (Button) findViewById(R.id.btnLLogin);
intent = getIntent();
successResponse.setText(intent.getStringExtra("successResponse"));
}
public void Login(View v) {
btnLLogin.setTextColor(getResources().getColor(R.color.black));
intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onBackPressed() {
finish();
}
}
please use intent = new Intent(LogoutActivity.this, LoginActivity.class); instead of intent = new Intent(this, LoginActivity.class);
beside this use
most important
Add android:launchMode="singleTask " to the activity element in your manifest for Activity LoginActivity

Categories

Resources