0

Android as a client side,i am sending data from client side to server side.Ruby on rails as server side,how to fetch data from client side using the post method.

I want to get the data from client side to server side to display. For client side i have code how to send data to server side,but in server i dont know how to fetch data.

By using server side only,we have to create url and that url ony we have to use in client side code for sending data.

serversidecode.

def load
    if signed_in?
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      @my_post = current_user.posts.new
    end
    @posts = Post.paginate(page: params[:page],:per_page => 10)
    @post = Post.new
  end


  def index
    @posts = Post.all
    respond_with(@posts) do |format|
      format.json { render json: @post_names = {:post => @posts.as_json(:only=> :content)} }
    end
  end 

  def show
    if signed_in?
      @post = Post.find(params[:id])
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      current_user.vote_for(@post)
    else
    @post = Post.find(params[:id])
    Guest.find(1).vote_for(@post)
    end
    @posts = Post.paginate(page: params[:page],:per_page => 10)  
    @guest = Guest.new
    @user = User.new
    @users = User.paginate(page: params[:page],:per_page => 10)
  end

  def create 
    @post = Post.new(params[:post])
    if @post.save
      @posts = Post.paginate(page: params[:page],:per_page => 10)
    else 
      @posts = Post.paginate(page: params[:page],:per_page => 10)
    end
    @guest = Guest.new
    @users = User.paginate(page: params[:page],:per_page => 10)

  end

  def my_prayer_create     
      @my_post = current_user.posts.new(params[:post])
      @post = Post.new(params[:post])
      @guest = Guest.new
      @user = User.new
      @users = User.paginate(page: params[:page],:per_page => 10)
      if @my_post.save
        flash[:notice] = "Prayer Successfully created."
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      else 
        flash[:notice] = "Error"
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      end
  end

  def edit
    if signed_in?    
    @my_post = current_user.posts.find(params[:id])
    else
    @post = Post.find(params[:id])
    end
  end

  def update
    if signed_in? 
      @my_post = current_user.posts.find(params[:id])
      if @my_post.update_attributes(params[:post])
        flash[:notice] = "Prayer Successfully updated."
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      end
    else  
    @post = Post.find(params[:id])
    end
  end

  def destroy
    if signed_in? 
      @my_post = current_user.posts.find(params[:id])
      @users = User.paginate(page: params[:page],:per_page => 10)
      @guest = Guest.new
      @my_post.destroy
      flash[:notice] = "Prayer Successfully destroyed."
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
    end
  end

This is the server side,how to do here to fetch data from client side.

Myclientside code also i mention here

public class HomeLayoutActivity extends Activity implements OnClickListener{

        private EditText value;
        private Button btn;
        private ProgressBar pb;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home_layout);
            value=(EditText)findViewById(R.id.editText1);
            btn=(Button)findViewById(R.id.button1);
            pb=(ProgressBar)findViewById(R.id.progressBar1);
            pb.setVisibility(View.GONE);
            btn.setOnClickListener(this);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.home_layout, menu);
            return true;
        }

        public void onClick(View v) {
            // TODO Auto-generated method stub
                if(value.getText().toString().length()<1){

                    // out of range
                    Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
                }else{
                    pb.setVisibility(View.VISIBLE);
                    new MyAsyncTask().execute(value.getText().toString());      
                }


        } 

        private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

            @Override
            protected Double doInBackground(String... params) {
                // TODO Auto-generated method stub
                postData(params[0]);
                return null;
            }

            protected void onPostExecute(Double result){
                pb.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
            }
            protected void onProgressUpdate(Integer... progress){
                pb.setProgress(progress[0]);
            }

            public void postData(String valueIWantToSend) {
                // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://localhost:3000/posts/create_a_post");

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("content", valueIWantToSend));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    //httppost.addHeader("Authorization","Basic "+authorization);
                    httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
                    //httppost.setHeader("Content-Type", "application/json");
                    httppost.addHeader("Accept", "application/json");

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block


                }
            }
        }
    }

How to get data from client side,what are the codes i have to do in ruby on rails

Karthick M
  • 791
  • 2
  • 9
  • 29

1 Answers1

0

You don't send Json to the server.

See similar question how to send Json data with Android: How to send POST request in JSON using HTTPClient?

If your Json is correct you can access your data in Rails with the params method, there will no difference in accessing params between a normal web request or an android client request.

You don't need to change the Rails code. Make a test request with an Http-Client.

I made a screenshot for an example request with HttpRequester:

enter image description here

The params post[name] and post[user_id] only examples, replace it with your attributes.

Your development server console should have following output after sending the request:

Started POST "/posts" for 127.0.0.1 at 2013-06-10 13:31:01 +0200
Processing by PostsController#create as HTML
  Parameters: {"post"=>{"name"=>"name", "user_id"=>"5"}}
Community
  • 1
  • 1
dan
  • 1,018
  • 8
  • 15
  • sorry i am not sending json,i am just sending simple text only like this nameValuePairs.add(new BasicNameValuePair("content", valueIWantToSend)); – Karthick M Jun 10 '13 at 10:13
  • you have an link for client side dude, i am having problem in server side ror dude – Karthick M Jun 10 '13 at 10:31
  • Your problem is that you not send correct data to the server, I gave you a link to send real json data with android, but if you only want to send key-value-pairs you have to set your Content-Type on client side to "application/x-www-form-urlencoded". Then you can easily access client data with the `params` method, as I mentioned. – dan Jun 10 '13 at 10:40
  • httppost.setHeader("Content-Type", "application/json"); is this correct,how to set in server side,can you look at my code and tell the error and what i want to change in my code@dan – Karthick M Jun 10 '13 at 10:45
  • set httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"), you didn't need any change on server side, you only have to send correct post data, then rails will do the rest – dan Jun 10 '13 at 10:51
  • is this my url is correct or not http://localhost:3000/posts ,then how can i check – Karthick M Jun 10 '13 at 10:52
  • its not changing anything dude,any other changes i want to do in server side code,and the url is correct? – Karthick M Jun 10 '13 at 10:58
  • URL is correct, the easiest way to test is with an HTTP-Client, e.g. use this plugin https://addons.mozilla.org/de/firefox/addon/httprequester/ for Firefox, there are similar ones for Chrome – dan Jun 10 '13 at 11:00
  • ya dude i check with rest client also,its not showing anything in that page@dan – Karthick M Jun 10 '13 at 11:02
  • dude in the post name i put the ""content" with the value pair,in my rest client it showing an empty.i changed the content type also – Karthick M Jun 10 '13 at 11:21
  • http://mobiledevtuts.com/android/android-http-with-asynctask-example/ this was taken for reference dude, for client side,but here in server side code they are using php,but for me in server side code ror is used – Karthick M Jun 10 '13 at 11:24
  • What does the params-Hash contains after sending the request? – dan Jun 10 '13 at 11:25
  • where dude,can you check my coding there – Karthick M Jun 10 '13 at 11:27
  • did you put `ressources :posts` in your routes.rb (dont't forget to restart your server)? If your correct action will be called you see the post parameters in the development server output in the console if you start your server with `rails server` – dan Jun 10 '13 at 11:33
  • ya dude,i put resources :posts this one in routes.rb also dude i restart the server same blank page only showing dude@dan – Karthick M Jun 10 '13 at 11:34
  • what is the console output of you test server when calling `localhost:3000/posts` ? – dan Jun 10 '13 at 11:40
  • console is not showing any error dudes,its showing succes only,even it shows output in avd,like after edit something and send na,it shows commandsend also showing. – Karthick M Jun 10 '13 at 11:43
  • I updated my answer with the expected console output, if is it not what you get, post your console output in your question. – dan Jun 10 '13 at 11:51
  • where i can see the console output dude – Karthick M Jun 10 '13 at 11:53
  • in the terminal/console where you started your development server – dan Jun 10 '13 at 11:54
  • i am not getting you correctly,where i have to see in android tool or command prompt or in rest client.in rest client and in web url shows blank page,in my android tool are also not showing any error in console – Karthick M Jun 10 '13 at 11:56
  • dude can i send my pjct to your,can you check it dude@dan – Karthick M Jun 10 '13 at 11:57
  • I am talking form your the server console of your rails app. Did you ever wrote an working rails application? If not I think you should start with this before trying sending data from android. – dan Jun 10 '13 at 12:02
  • dude i dont know how to check in server console,how to do that thing – Karthick M Jun 10 '13 at 12:12
  • how do you start your rails server? – dan Jun 10 '13 at 12:16
  • in compand prompt i typed rails s – Karthick M Jun 10 '13 at 12:17
  • super, this is your server console, their you should see the output for every request – dan Jun 10 '13 at 12:20
  • Dude like Started POST this like line no line in my server console all are liek this only started get – Karthick M Jun 10 '13 at 12:26
  • http://pastebin.com/KeTk5eGm can u see this link,here i put that full controller and routes.rb code you can check dude,i am struggling a lot – Karthick M Jun 10 '13 at 12:28
  • ok, I finish my help here, look at your english of your last comment, I am not guessing what you are trying to explain. I gave you all what you need to send data from android to your rails app. If you do not understand my tipps I can't do anything for you. – dan Jun 10 '13 at 12:33
  • sorry dude,i checked the server console what you mention the above comment,there is not Started post line in my server console,here i gave my coding link also can you check it dude http://pastebin.com/KeTk5eGm can you look at my code and tell dude anyother changes i want to do in code@dan i am also trying all the ways what you are telling dude. – Karthick M Jun 10 '13 at 12:36
  • my last tip for you, remove `respond_to :json, :xml` from `PostsController` as you don't send any json or yml. – dan Jun 10 '13 at 12:36
  • No dude actually i am sending json also from server side to client side its working fine dude,but vice versa that is client side to server side thats only problem dude @dan – Karthick M Jun 10 '13 at 12:38
  • have you seen code what i mention in that link,is this anything i want to change dude – Karthick M Jun 10 '13 at 12:48