Passing one String from Activity A to Activity B

Put your problem here if it does not fit any of the other categories.

Re: Passing one String from Activity A to Activity B

Postby Phyll » Thu Feb 16, 2012 8:19 pm

Hey Marbert,

The problem is, it is probably more complicated to make your example work than it is to make the real program work. But what I was trying to explain in my previous post is that you pass things like the string back and forth between activites the same way we have been all along, with the extras in intents. I would assume you send back the result of your spinner selection the same way. To do that in your example here we would need to intercept the back button. Is that what you need?

Because here is how you do that:

Code: Select all
    @Override
    public void onBackPressed() {

            String sToSend = txtValue.getText().toString();
            Intent in = new Intent();
            in.putExtra("value", sToSend);
            Settings.this.setResult(RESULT_OK, in);
            finish();

        return;
        }//onbackpressed


You would need to send this back to the choose activity at least to store it until you push the other button and send it on to the main activity.

Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Top

Re: Passing one String from Activity A to Activity B

Postby Marbert » Thu Feb 16, 2012 8:38 pm

Hi Phyll,

The back-button was only how to get back to the Choose-Activity when being in another Activity. ;)
I just thought picking out the problem in an extra app would be easier. I did the same with reading in the file. So I just concentrate on one problem. After everything's working I put together all pieces in the real app.

So the user just enters text into Settings-Activity and this text should be displayed in the Main-Activity.

In the third post of this topic we were on a good way. But I just got a 'null' back...

But I'll try and if I get the code working I'll post the solution here. ;)

Thanks for all your help,
Marbert
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Thu Feb 16, 2012 9:16 pm

Hey Marbert,

Then you will probably want to make choose look like this:

Code: Select all
   String storage = "";
   private static final int GET_STRING = 1;
   
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chooselayout);
       
        btnChToM = (Button) findViewById(R.id.btnChToM);
        btnChToM.setOnClickListener(this);
       
        btnChToSet = (Button) findViewById(R.id.btnChToSet);
        btnChToSet.setOnClickListener(this);
       
 
        //When pressing here, the user gets to the MainActivity
        btnChToM.setOnClickListener(new View.OnClickListener()
      {
         public void onClick(View v)
         {
            Intent iChToM = new Intent(Choose.this, MainActivity.class); //Go to Main
            
            iChToM.putExtra("value", storage);
            
            startActivity(iChToM);
         }
       
      });
       
        //When pressing here, he gets to the Settings:
        btnChToSet.setOnClickListener(new View.OnClickListener()
        {
         public void onClick(View v)
         {
            Intent iChToSet = new Intent(Choose.this, Settings.class); //Go to Main
            
               iChToSet.putExtra("value", storage);

            startActivityForResult(iChToSet, GET_STRING);
         }
      });
       


       
    }//oncreate
   
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
             if (requestCode == GET_STRING) {

               storage = data.getStringExtra("value");
               
               
                }//getstring
            }//if result_ok
        }//onactivityresult


The settings look like this:

Code: Select all
   @Override
    public void onBackPressed() {

            String sToSend = txtTextSet.getText().toString();
            Intent in = new Intent();
            in.putExtra("value", sToSend);
            Settings.this.setResult(RESULT_OK, in);
            finish();

        return;
        }//onbackpressed


And the main look like this:

Code: Select all
        Intent startingIntent = getIntent();
       String mString = startingIntent.getStringExtra("value");
       
        tvMain = (TextView) findViewById(R.id.tvMain);
        btnGetString = (Button) findViewById(R.id.btnGetString);
       
        tvMain.setText(mString);
       
       
        //After pressing this button, the String from the Settings-Activity should be shown here in this Activity in the TextView tvMain:
        btnGetString.setOnClickListener(new View.OnClickListener()
      {
         public void onClick(View v)
         {
            try
            {

                   Intent i = new Intent(MainActivity.this, Settings.class);
                   startActivityForResult(i, GET_STRING);

            }
            catch (Exception e)
            {
               e.printStackTrace();
               Toast ng = Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT);
               ng.show();
            }   
         }
      });
    }//oncreate

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
             if (requestCode == GET_STRING) {

               tvMain.setText(data.getStringExtra("value"));
               
               
                }//getstring
            }//if result_ok
        }//onactivityresult


Hope this helps. My copy is working.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Passing one String from Activity A to Activity B

Postby Marbert » Thu Feb 16, 2012 9:27 pm

Thanks a lot, I'll try it and give feedback!

How long have you been developing apps for Android? :-)
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 12:15 am

Hi Phyll,

We're are almost there, thanks for the code!!
Just one more thing (I know, I'm a little bit annoying ;)):
I just have to figure out how to skip this window (I've attached a screenshot) after pressing the button. Then it's perfect.

After pressing the button the user should directly see the text in the TextView.

Thanks,
Marbert

EDIT: and why do we need private static final int GET_STRING = 1;? What exactly does it do? Just to prove if something is right/false (like a boolean)?
Attachments
Screenshot_2012-02-16-23-10-45 (240 x 400).jpg
Screenshot_2012-02-16-23-10-45 (240 x 400).jpg (6.77 KiB) Viewed 182 times
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Fri Feb 17, 2012 5:39 am

Hi Marbert,

About two and half years. That's how long I've been working with Android. I've been writing programs for various machines for over thirty. I really never used Java until Android came along. I'm generally a Pascal guy. I use C# some nowadays and its a lot like Java I think. I'm strictly a Windows guy. Apple and I parted ways when they decided to manage the "user experience" completely and left the "enthusiasts" like me behind (Macintosh). When I saw the iPhone I knew I had to do something with this new technology but you have to have Apple equipment to work on the iPhone. So that left Android as the only viable alternative. It wasn't very long before I had one.

Here's an example of how those "constants" might be used:

public static final int DO_FORM_1 = 1;
public static final int DO_FORM_2 = 2;
public static final int DO_FORM_3 = 3;
public static final int DO_FORM_4 = 4;

Generally it's good form to use a constant where the same value will be used more than once, it can be named and its name can describe what it is used for. Of course you could just put a zero or a one or something in there and forget about the constant. When each of these values are used to start a different form in a form activity or the like, that same id is returned to the onActivityResult() so you can use a switch block to decode which form or activity is being returned and act appropriately. This isn't a very elaborate program so it really doesn't matter much. Its just the proper way.

Once again I think I'm missing the point. Where does the text come from if its not entered in the settings activity in one way or another? Are you wanting to load it from some where like preferences or something?

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Top

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 12:02 pm

Hi Phyll!

Wow, sounds quite interesting! :)


Imagine you have written your own text editor. In your settings you can set a place to save your files. Normally you set this place once and all your written files are saved in the same folder. You don't want to be asked every single time where to save your files - it should be done automatically.

And that's my problem. I've tried a lot with intents (I've never done before anything with them, I'm new to Android, so it's quite difficult, but I love trying things like this ;)). And I think your last suggestion is nearly perfect. I just want to 'skip' this window.

I hope this explains my problem a little bit better.


Thanks,
Marbert
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Fri Feb 17, 2012 1:58 pm

Hi Marbert,

There are a couple of things you can do.

I don't have to imagine it. I've done it. B&P Software (my company) has just such an editor. It creates a folder on the sdcard called BPE. That's pretty easy to do. When your app starts, it checks for the external storage and creates a BPE folder if one doesn't exist. Then it just uses that folder. The file picker for that program always starts there but it can move down to the sdcard itself or anywhere you are allowed to. Need root privileges to get very far.

You could also make a folder in the /data/data/com.your.package.name folder. Same thing, if it exists use it, if not create it.

Here's some code that does that:

Code: Select all
        //Find our folder
        File extStore = Environment.getExternalStorageDirectory();
        String ss = extStore.getPath()+DEFAULT_PATH;
        TextFile tf = new TextFile(this,ss,MAIN_FILE);
        if (!tf.CheckPath()) Log.e("CHECKPATH","Error "+ss);
            else dataPath = ss;


This relies on a textfile class that I made:

Code: Select all
package com.bandpsoftware.scrambler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;

import android.content.Context;
import android.util.Log;

public class TextFile {

   public static boolean PRIVATE_MODE = false;
   public static boolean PUBLIC_MODE = true;

    private String pathStr;
    private String fileStr;
    private boolean mode;
    private Context con;

   public TextFile(Context context, String path, String filename) {
       pathStr = path;
       fileStr = filename;
       mode = PRIVATE_MODE;
       con = context;
       }//constructor

   public boolean CheckPath() {
       try {
             File file = new File(pathStr);
              if (file.exists()==false) {
                if (file.mkdir()==false) return false;
                  }//if no file yet
            }//get main folder
            catch (Exception e) {
                Log.e("CHECKPATH","Error "+e.getMessage());
               return false;
               }//catch
        return true;
       }//checkpath

   public boolean writeTextFile(String text) {
       byte[] buffer;
       FileOutputStream fos;
       try {
            String fs = MakeFileName();
            if (mode==PUBLIC_MODE) fos = new FileOutputStream(fs);
                else fos = con.openFileOutput(fs, Context.MODE_PRIVATE);
           buffer = text.getBytes("UTF-8");
           fos.write(buffer, 0, buffer.length);
           fos.close();
           return true;
           }//try
           catch (IOException e) {
               Log.d("WRITEFILE","Error "+e.getMessage());
               return false;
               }//catched
       }//writetextfile

   public boolean appendTextFile(String text) {
       byte[] buffer;
       FileOutputStream fos;
       try {
            String fs = MakeFileName();
            if (mode==PUBLIC_MODE) fos = new FileOutputStream(fs,true);
                else fos = con.openFileOutput(fs, Context.MODE_PRIVATE|Context.MODE_APPEND);
           buffer = text.getBytes("UTF-8");
           fos.write(buffer, 0, buffer.length);
           fos.close();
           return true;
           }//try
           catch (IOException e) {
               Log.d("APPENDFILE","Error "+e.getMessage());
               return false;
               }//catched
       }//appendtextfile   
   
    public String readTextFile() {
        int b;
        String buf="";
        byte[] buffer = new byte[1000];
        FileInputStream fis;
        try {
           String fs = MakeFileName();
            if (mode==PUBLIC_MODE) fis = new FileInputStream(fs);
                else fis = con.openFileInput(fs);
            do {
                b=fis.read(buffer);
                if (b>-1) buf=buf+new String(buffer,0,b,"UTF-8");
                }//do
            while (b!=-1);
            fis.close();
            return buf;
            }//try
            catch (IOException e) {
                Log.d("READFILE","Error "+e.getMessage());
                buf = "";
                }//catched it
        return buf;
        }//readtextfile

   private String MakeFileName() {
        String s = "";
        mode = PRIVATE_MODE;
        if (pathStr.length()!=0) {
            File file = new File(pathStr);
            s = file.toString()+"/";
            mode = PUBLIC_MODE;
           }//get path name
       s = s+fileStr;
       return s;
       }//makefilename

}//class


Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 2:22 pm

Hi Phyll,

Thanks, but saving and reading is already working. ;)
But I only have a String filename, it's "/sdcard/read.txt". This path isn't the same on all devices. So let's say I want it to work on every device I have to change it to "extStore.getPath()+read.txt"?

First I wanted to fix the String-problem. I think it isn't this difficult, but am I explaining it badly?

I need to pass a String from Activity A (Settings) to Activity B (Main).

This should be done: user inserts the path to the *.txt-file he wants to read in, this is in the TextView which is located in the Settings-Activity.

The default value is entered this way in the settingslayout.xml: android:text="@string/sDefault".
But the user can change this path if his *.txt-file has another name or is located in another place. And he should just change this value when he wants to do it, not every single time he reads in a file.
Maybe it's a bad comparison, but: you have the Path-variable in Windows. It has a default value, normally everything should work fine with this value. It's globale and is important for the whole OS. If you want you can add/remove things from this variable.

THe same is with my String in Settings. There's a default value and if the file is named read.txt there are no problems. But if it isn't named like this the user can change it. He can change it at any times HE wants. If he doesn't want to change the app works with the value which currently is in the EditText.

Thanks,
Marbert
(sorry for the (bad) English, it's not my native language ;))
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Fri Feb 17, 2012 4:20 pm

Hi Marbert,

This part of the previous post:

File extStore = Environment.getExternalStorageDirectory();
String ss = extStore.getPath()+DEFAULT_PATH;

gets you the true external storage location on that device which, as you said, is not always sdcard. After version 2.something I don't think it will be again. So yes you would need to find out what it is before you add your text file to it. I don't think it returns with a "/" on the end of it so DEFAULT_PATH has to have it, "/read.txt".

The TextFile class works pretty good, you shouldn't dismiss it so easily. I use it all the time. But if you don't want to use it, just get rid of it. It just makes that piece of code work.

To pass a string from one activity to another. That's what this thread is titled and what we have gone over a dozen times. Whatever activity comes up and runs first, needs to read this value from somewhere so that it can pass it on and whatever activity comes next can get it from the starting intent and display it, edit it, use it, whatever.

I think that concentrating on the individual parts is preventing me from seeing the bigger picture and I am missing the vital flow of the program from part to part. But I think that is what you keep asking about and want it explained in terms of the parts. I must not be doing a very good job of that either. I know I don't think like that and maybe that is part of the problem.

It seems to me like, your app can't wait until the settings activity to have that value and before that it doesn't exist if that's where it is gotten. It needs to be gotten in the first activity, Choose if that's what it is called, and Choose needs to be part of this discussion as it is, not as an empty routine with only a fraction of its functionality. It makes it difficult for me to grasp your requests because you know what is missing but I don't. It makes it difficult but hopefully not impossible.

Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 4:36 pm

Hi Phyll,

Ok, thanks for the explanation!
May I ask you a question? Which information do you need for helping me? :)


Thanks,
Marbert
Attachments
SCAN0022 (624 x 520).jpg
SCAN0022 (624 x 520).jpg (59.38 KiB) Viewed 148 times
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Fri Feb 17, 2012 9:16 pm

Hi Marbert,

I don't know if I'm catching on yet or not but I worked on ActivityString some more and here is the latest version. Perhaps we can figure this out by refining this. Please try it out and let me know what's right or wrong about it.

I'm somewhat stuck on the things that refer to the settings as a container. That is, the other activities get values from that activity. That is throwing me because you know 3.1 on your chart only exists while it is on the screen. In the other activities it is not possible to get values from it without running it. Kind of throws me.

Hope this helps.

Phyll
Attachments
ActivityString2B.zip
ActivityString2B Example
(68.89 KiB) Downloaded 21 times
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 9:40 pm

Perfect, Phyll, just perfect. :)

Thank you very much! This is exactly what I wanted to have!

Thanks a lot,
Marbert

EDIT: one last question: when I open the app and directly go to main (I don't open the Settings) and press the button, just 'Default' is displayed. What's the best way to set a value if Settings wasn't open before?

Would this work? I set a globale constante. If Settings was opened, it's 1, if it wasn't it's 0 and I take a string which is located in Main?
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Re: Passing one String from Activity A to Activity B

Postby Phyll » Fri Feb 17, 2012 10:29 pm

Hi Marbert,

Good it sounds like we are making some progress!

Your system can work. You would be setting a semaphore to be used by the program. I still can't wrap my head around getting the value "located in main". I think ultimately what would/could be done is to store that filename in the preferences and load it on program start up. Keep it up to date if it changes. Send it to the settings activity for editing and the main for using. You see?

Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Passing one String from Activity A to Activity B

Postby Marbert » Fri Feb 17, 2012 10:39 pm

Hi Phyll,

'Located in Main' just means a string in the Main-Activity. ;)
Basically I know what you mean. But I'll try tomorrow, I'm too tired right now.

Thanks for all you have done!

Marbert
Marbert
Developer
Developer
 
Posts: 30
Joined: Sat Feb 04, 2012 7:31 pm

Top
PreviousNext

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 16 guests