android : can't delete and remove sharedpreferences file - java

i have posting question in here but i got nothing, so i decide to make a new question for searching other solution.
this is my case : First, I was using Shared preferences for my application for sending data from one activity to another, when listview is clicked in first activity, it will going to detail. when other list is clicked, it will going to first data that i've clicked before it. then i realize if i use sharedpreferences for sending data from one activity to other activity, it will save in device memory, so i change my code and decide to use intent, but my sharedpreferences's file is not remove. when list is clicked, it will going to first data that i've clicked when i use shared preferences.
I have used:
settings.edit().clear().commit();
and
settings.edit().remove().commit();
but i think it doesn't work. this is my first activity using intent:
public class TerbaruSimasCard extends ListActivity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
private ProgressDialog dialog;
private ArrayList<TerbaruModel>ListTerbaru;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruSimasCard.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruSimasCard.this, true);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
super.onCreate(savedInstanceState);
setContentView(R.layout.terbarusimascard);
ListTerbaru= new ArrayList<TerbaruModel>();
new TerbaruAsyncTask().execute();
}
public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
String url = ("http://www.abc.xyz/sc_merchant.htm?s=3&d=25");
public TerbaruAsyncTask() {
this.url=url;
}
protected void onPreExecute (){
super.onPreExecute();
dialog = ProgressDialog.show(TerbaruSimasCard.this,"", "melakukan pengambilan data...");
}
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
result= Connection.get(url);
} catch (Exception e){
result = "";
Log.d("test", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute (String result){
super.onPostExecute(result);
fetchResponse(result.replace("\n","").trim());
dialog.dismiss();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent detail= new Intent (TerbaruSimasCard.this, TerbaruDetail.class);
detail.putExtra("nama", nama1);
detail.putExtra("alamat",alamat1);
detail.putExtra("ket", ket1);
detail.putExtra("telp",telp1);
detail.putExtra("begdate", begdate1);
detail.putExtra("enddate",enddate1);
detail.putExtra("img_id", img_id1);
System.out.println(nama1);
startActivity (detail);
}
});
}
}
private void fetchResponse (String result){
if (!result.equals("")){
try {
JSONArray jsonArray = new JSONArray(result);
TerbaruModel LT=null;
for (int i= 0; i < jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject (i);
LT= new TerbaruModel (jsonObject.optString("kat"),
img_id1=jsonObject.optString("img_id"),
nama1= jsonObject.optString("nama"),
alamat1=jsonObject.optString("alamat"),
ket1=jsonObject.optString("ket"),
jsonObject.optString("tgl"),
jsonObject.optString("accday"),
telp1=jsonObject.optString("telp"),
begdate1=jsonObject.optString("begdate"),
enddate1=jsonObject.optString("enddate")
);
ListTerbaru.add(LT);
list=(ListView)findViewById(android.R.id.list);
setListAdapter (new TerbaruAdapter(this, ListTerbaru));
}
this is for detail:
public class TerbaruDetail extends Activity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
#Override
public void onCreate (Bundle savedInstanceState){
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruDetail.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruDetail.this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.detailviewer);
Intent detail= getIntent();
nama1=detail.getStringExtra("nama");
alamat1= detail.getStringExtra("alamat");
ket1= detail.getStringExtra("ket");
img_id1= detail.getStringExtra("img_id");
telp1= detail.getStringExtra("telp");
begdate1= detail.getStringExtra("begdate");
enddate1= detail.getStringExtra("enddate");
System.out.println(nama1+"nama");
TextView detail_phone=(TextView) findViewById(R.id.detail_phone);
TextView detail_begdate=(TextView) findViewById(R.id.begdate);
TextView detail_enddate=(TextView) findViewById(R.id.endate);
TextView detail_name =(TextView) findViewById(R.id.detail_name);
TextView detail_adress =(TextView) findViewById(R.id.detail_adress);
TextView keterangan =(TextView) findViewById(R.id.keterangan);
ImageView detail_img_id= (ImageView) findViewById(R.id.img_kategori);
detail_name.setText(nama1);
detail_phone.setText(telp1);
detail_begdate.setText(begdate1);
detail_enddate.setText(enddate1);
detail_adress.setText(alamat1);
keterangan.setText(ket1);
}

If You do not mind just delete the app then reload the apk.
From what I know the Shared Preferences value will remain until you uninstall an app.
If the above did not work then try to deleted manually
/data/data/com.package.name/shared_prefs/PREFS_NAME.xml

If you just want to clear out your data (because it is corrupt or whatever), you can do that manually from the home screen. setting -> application manager -> "your app" -> clear data

SharedPreferences.Editor.clear() will not delete the sharedpreferences file, it only clears the contents in this file.
If you really want to delete this file, you should use file operation , sharedprefereces file location is /data/data/com.yourpackage.name/shared_prefs/filename.xml. BTW, you'd better use intent to send data between activities.

Related

Android resume activity variables gone

Short:
I have Three classes: A (MainActivity), B (Secondary), C(Third).
A is parent of B is parent of C.
In A I make an Intend with Extra int idForUsage on B. B stores idForUsage in a variable int chosenId(works fine).
B does Stuff and makes an Intent with Extra int chosenId and int secondIdForUsage(works also fine).
C does Stuff and it works all fine.
When I´m now clicking the litte "back button" in the upper left corner to get to the parent activity the app crashes because I´m trying to access the Variable chosenId which seems to being set to default -1 (even if I´m trying to read the Extra again.)
public class MainActivity extends AppCompatActivity {
//references to Buttons etc
...
public static final String ChosenID = "com.example.Abzeichenschwimmer.ChosenSwimmerID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up button stuff
...
//ListView which has clickable Items which trigger the Activity
lv_swimmerList = findViewById(R.id.lv_schwimmerListe);
//Listeners
lv_swimmerList.setOnItemClickListener(this::onListViewItemClick);
}
#Override
protected void onResume(){
super.onResume();
updateSchwimmerliste(dataBaseHelper);
}
public void onListViewItemClick(AdapterView<?> parent, View view, int position, long id) {
SchwimmerModel clickedSchwimmer = (SchwimmerModel) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, DisplaySchwimmer.class);
//Toast.makeText(MainActivity.this, String.valueOf(clickedSchwimmer.getId()), Toast.LENGTH_SHORT).show();
intent.putExtra(ChosenSwimmerID, clickedSchwimmer.getId());
startActivity(intent);
}
}
public class DisplaySchwimmer extends AppCompatActivity {
int chosenSwimmerID;
public static final String SchwimmerID = "com.example.Abzeichenschwimmer.schwimmerID";
public static final String AufgabenID = "com.example.Abzeichenschwimmer.aufgabenID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_schwimmer);
lv_exc = findViewById(R.id.lv_aufgaben);
refreshValues();
showAufgabenOnListView(dataBaseHelper);
lv_exc.setOnItemClickListener(this::onListViewItemClick);
}
public void getIntentExtra(){
Intent intent = getIntent();
chosenSwimmerID = intent.getIntExtra(MainActivity.ChosenSwimmerID,-1);
}
public void onDeleteClick(View view){
SchwimmerModel toDeleteSwimmer = (SchwimmerModel) dataBaseHelper.getSchwimmerByID(chosenSwimmerID);
dataBaseHelper.deleteSchwimmer(toDeleteSwimmer);
Toast.makeText(this, "deleted", Toast.LENGTH_SHORT).show();
DisplaySchwimmer.this.finish();
}
public void refreshValues(){
getIntentExtra();
SchwimmerModel schwimmer = dataBaseHelper.getSchwimmerByID(chosenSwimmerID); <--- Main Error
}
private void showAufgabenOnListView(DataBaseHelper dataBaseHelper) {
getIntentExtra();
ArrayAdapter<ExcerciseModel> schwimmerArrayAdapter = new ArrayAdapter<ExcerciseModel>(DisplaySchwimmer.this, android.R.layout.simple_list_item_1, dataBaseHelper.getExcersisesForSwimmerByID(chosenSwimmerID));
lv_exc.setAdapter(schwimmerArrayAdapter);
}
public void onListViewItemClick(AdapterView<?> parent, View view, int position, long id) {
ExcerciseModel clickedExcerciseModel = (ExcerciseModel) parent.getItemAtPosition(position);
Intent intent2 = new Intent(DisplaySchwimmer.this, DisplayAufgabe.class);
intent2.putExtra(SchwimmerID, chosenSwimmerID);
intent2.putExtra(AufgabenID, clickedExcerciseModel.getId());
Log.e("aaa", String.valueOf(chosenSwimmerID));
startActivity(intent2); <-- Intentstart
}
#Override
protected void onResume(){
super.onResume();
showAufgabenOnListView(dataBaseHelper);
}
}
I hope the code (deleted many lines) is ok for an overview. Maybe someone knows the solution for this.
Thanks Maximus
When you press back from DisplayAufgabe to DisplaySchwimmer (the intent always is null)
Because you call getIntent di DisplaySchwimmer, you will get default value which is -1 (null intent extra)
When you try to call dataBaseHelper.getSchwimmerByID(chosenSwimmerID); is mean you try to get index -1 on database. You will always get error because accessing index -1.
My Suggestion
Add validation before call dbHelper i.e
if (chosenSwimmerID > -1){
SchwimmerModel schwimmer = dataBaseHelper.getSchwimmerByID(chosenSwimmerID);
}
Only getExtra when value available
if (intent.hasExtra(MainActivity.ChosenSwimmerID)){
chosenSwimmerID = intent.getIntExtra(MainActivity.ChosenSwimmerID,-1);
}
It all boiled down on using sharedPreferences. This helped a lot. A Second post from me explanined this problem more simplified and I found a solution.

How To Save Changes made To The Items of A list

My app displays a customed list of videos with the option to download using IntentService. The custom list is displayed on the UI using a recyclerView system. Below is a pic of the list
When a video is clicked and downloaded, the download icon turns blue as seen in the first child of the list shown in the picture above and when it has not been downloaded it shows the default black download icon. I have strung up some codes to make it work, the challenge is, when the app is restarted, The download icon revert to its default color even when it was previously downloaded. How do I update and save changes made to the color of the download icon so it will reflect when the app is restarted? I understand the SharedPreference class can be used to save changes made to the App, but I don't know how to achieve this. Would appreciate any assist that can be lent to achieve this
Below is my onCreate mtd
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecture);
setUpRecyclerView();
And below is where I created the setUpRecyclerView()
private void setUpRecyclerView() {
Query query = lectureRef.orderBy("position", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<LectureClasses> options = new FirestoreRecyclerOptions.Builder<LectureClasses>()
.setQuery(query, LectureClasses.class).build();
adapter = new LectureClassesAdapter(options);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
Below is my call of the onViewItemclick #overide method setup in my adapter class
#Override
public void onViewItemClick(DocumentSnapshot snapshot, int position, View itemView) {
//init variables
CircularProgressBar progressBarCir = itemView.findViewById(R.id.progress_circular);
progressBarCir.setProgressMax(100f);
ImageView downloadImage = itemView.findViewById(R.id.download);
PopupMenu popupMenu = new PopupMenu(LectureActivity.this,downloadImage);
LectureClasses lectureClasses = snapshot.toObject(LectureClasses.class);
lectureClasses = adapter.getItem(position);
String titleNow = lectureClasses.getTitle();
String urlNow = lectureClasses.getUrl();
class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
progressBarCir.setProgress(progress);
downloadImage.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS","DOWNLOADING>>>");
if (progress == 100) {
progressBarCir.setVisibility(View.GONE);
downloadImage.setImageDrawable(getDrawable(R.drawable.download_blue));
downloadImage.setVisibility(View.VISIBLE);
}
}else {
Log.i("STATUS"," NOT DOWNLOADING,BOSS");
}
}
}
}
you are can to check the file with below code
File videoFile = new File("patch_video_file");
if (videoFile.exists()){
// visible button blue
}else {
// visible button default
}

How to change the background color of a view from a different activity in android?

I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.
Here is the code :
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return numOfSets;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.
You've two options to change the color with two different life cycle of the change.
To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.
To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:
//store the value from ScoreActivity after completion as
TinyDB tinyDB = TinyDB(this);
tinyDB.putBoolean("isSet1Completed",true);
//access the boolean variable in SetsActivity to change the color of any set that
//is completed and if it's true, just change the color.
TinyDB tinyDB = TinyDB(this);
Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
But, it's your choice what way you want to prefer.
Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.
Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.
Declare it as public static ImageView imageview;(or TextView) intialize it in the
onCreated() as imageView = finViewById(R.id.viewId); in Sets activity. Call
it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.
Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.
I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.
I think simply you add flag in MainActivity.
for example, add flag in MainActivity.
boolean isFromDone = false;
and when done clicked,
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
and in MainActivity, add this.
#Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
Suppose you have a Linear Layout in Activity A and you want to change it's background color from a button click which is present in Activity B.
Step 1 Create a class and declare a static variable.
class Util { private static LinearLayout mylayout ; }
Step 2
In the activity which is holding this layout, initialize it.
Util.mylayout = findviewbyid(R.id.linear);
Step 3Change the background color on button click from Activity B
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}

How to display seekBar value and selected spinner item from Activity A to Activity B?

I have a listView in Activity A , which the value are returned from Activity B.When the list is clicked, it will intent to Activity B for edit.
Activity B
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_details_information);
addItemsOnSpinner();
if(getIntent().getExtras()!=null) // if has value pass from A
{
final String Project1=getIntent().getStringExtra("ReceiveProject");
final String Description1=getIntent().getStringExtra("ReceiveDescription");
final String Progress1=getIntent().getStringExtra("ReceiveProgress");
final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
//project.setText(Project1);
description.setText(Description1);
//progressText.setText("Covered:")
timeIn.setText(TimeIn1);
timeOut.setText(TimeOut1);
}
save.setOnClickListener(new View.OnClickListener()
{ // return to A
#Override
public void onClick(View v)
{
Intent returnIntent=new Intent();
Project=project.getSelectedItem().toString(); // Spinner Value
Description=description.getText().toString(); //from editText
progress=seekBar.getProgress(); // From SeekBar
returnIntent.putExtra("Project",Project);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("progress", progress);
Toast.makeText(getApplicationContext(), progress+"", Toast.LENGTH_LONG).show();
returnIntent.putExtra("TimeIn", TimeIn);
returnIntent.putExtra("TimeOut",TimeOut);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
public void addItemsOnSpinner()
{
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add("TRN-XXX-XXX");
list.add("Pro-XXX-XXX);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
}
Activity A
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveProject", ReceiveProject);
i.putExtra("ReceiveDescription", ReceiveDescription);
i.putExtra("ReceiveProgress", ReceiveProgress);
i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
I know that we can use setText to display the passed value from A to B for editText, but how about the spinner and seekBar value ?
This is the listView in Activity A. Value are returned from Activity B.
When listView is clicked, it will goes to B again to edit.
So how can I make the spinner in B display Pro-XXX-XXX and the seekBar goes to 48 ? Any idea or suggestion ? Thanks a lot
Edited
After used the answer from #Clairvoyant, now I get this (for spinner value).
Activity A
There are 4 list in Activity A.
Assume first list is clicked.
Everything works fine just the spinner(Project/Service/Training) display wrong value. It display the spinner value from last list(PRO-SKM-D5) instead of itself(Pro-XXX-XXX)
First Step: Make your addItemsOnSpinner like as below:
public void addItemsOnSpinner(String value)
{
int position = 0;
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add(position,"TRN-XXX-XXX");
list.add("Pro-XXX-XXX");
for(int i=0; i<list.size() ; i++){
if(list.get(i).equalsIgnoreCase(value)){
position = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
project.setSelection(position);
}
Second Step: call the above method when you are assigning value to the variable you have to show in spinner here for eg: project1 is the string value which you want to show in spinner then call the method as follows:
final String Project1=getIntent().getStringExtra("ReceiveProject");
addItemsOnSpinner(Project1);
Use SharedPreferences. Next time, googling helps.
Get SharedPreferences
SharedPreferences prefs = getDefaultSharedPreferences(context);
Read preferences:
String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);
To edit and save preferences
SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();
Shorter way to write
prefs.edit().putString(key, "Value").commit();
Additional info for SharedPreferences: JavaDoc and Android Developers Article

setText on button from another activity android

I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.

Categories