Java Android Program to Send and Receive Data From Server

«
»
Here is source code of the Program to Send and Receive Data From Server. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

U send and receive data from server using Google Cloud Messaging. For more information go to :- http://developer.android.com/google/gcm/index.html

Using Google cloud messaging would demand you to set up your own server either on your local host or on the internet , using Google App engine would be beneficial in such a scenario and yes there are other methods too to set up your server. The most important thing however is how to communicate between your application and server . The following code demonstrates how to send and receive data from server set up at parse.com which has already implemented server coding for , you just need to use there Api to send and receive data for more info for setting up a server go through the parse tutorials – www.parse.com

advertisement

Add

package com.example.travelplanner;
 
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class Addpool extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addpool);
        Parse.initialize(this, "PTVK87QK142x3t2xfuVI1HUN5ahNj1IBaynivYZA",
                "a4kY2kTmf55Uj9wpaTs44dkKhnUCjUNx8AxJpx9C");
        ParseAnalytics.trackAppOpened(getIntent());
 
        final EditText name = (EditText) findViewById(R.id.pool_name);
        final EditText time = (EditText) findViewById(R.id.pool_time);
        final EditText date = (EditText) findViewById(R.id.pool_date);
        final EditText endloc = (EditText) findViewById(R.id.pool_end);
        final EditText strtloc = (EditText) findViewById(R.id.pool_start);
        // intialize the entry here
        final ParseObject carpool = new ParseObject("Pool");
        Button sub = (Button) findViewById(R.id.pool_submit);
        sub.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String date1 = date.getText().toString();
                String time1 = time.getText().toString();
                // check what is coming here
                Log.i("date", date.getText().toString());
                if (date1 == "" || time1 == "") {
 
                    Toast.makeText(getApplicationContext(),
                            "Enter both date amd time", Toast.LENGTH_LONG)
                            .show();
                } else {
                    carpool.put("date", date.getText().toString());
                    carpool.put("name", name.getText().toString());
                    carpool.put("time", time.getText().toString());
                    carpool.put("strt_loc", strtloc.getText().toString());
                    carpool.put("end_dest", endloc.getText().toString());
                    carpool.put("pool", "iiitd");
                    carpool.saveInBackground();
                    startActivity(new Intent(Addpool.this, Pool_choose.class));
                }
            }
        });
    }
 
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
 
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        onDestroy();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.addpool, menu);
        return true;
    }
 
}

I have used Action-bar Pull to Refresh library u can find this and a lot of other fun libraries at www.androidviews.net.
Actvity_Main

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
package com.example.travelplanner;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
 
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
 
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import com.parse.ParseQuery;
 
//have to add a navigation drawer here later change to android list view here -- to be done later
@SuppressLint("SimpleDateFormat")
public class Carpool extends ListActivity implements
        PullToRefreshAttacher.OnRefreshListener {
 
    List<SmsFormat> List = new ArrayList<SmsFormat>();
    private PullToRefreshAttacher mPullToRefreshAttacher;
 
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
 
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        onDestroy();
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // get the data from the server and display it here
        Log.i("list adapter set", "adapter");
        get();
        mPullToRefreshAttacher = PullToRefreshAttacher.get(this);
        mPullToRefreshAttacher.addRefreshableView(getListView(), this);
 
    }
 
    public void get() {
 
        Parse.initialize(this, "PTVK87QK142x3t2xfuVI1HUN5ahNj1IBaynivYZA",
                "a4kY2kTmf55Uj9wpaTs44dkKhnUCjUNx8AxJpx7C");
        ParseAnalytics.trackAppOpened(getIntent());
 
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Pool");
        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(this);
        String src_loc = settings.getString("source_location", "n/a");
        String dest_loc = settings.getString("dest_location", "n/a");
 
        query.whereEqualTo("end_dest", dest_loc);
        query.whereEqualTo("strt_loc", src_loc);
        query.findInBackground(new FindCallback<ParseObject>() {
 
            @Override
            public void done(List<ParseObject> objects,
                    com.parse.ParseException e) {
                // TODO Auto-generated method stub
                if (e == null) {
                    Log.d("objects", "Retrieved " + objects.size());
                    for (ParseObject i : objects) {
                        SmsFormat message = new SmsFormat();
                        Log.i("date", i.getString("date"));
                        SimpleDateFormat formatter = new SimpleDateFormat(
                                "dd/MM/yyyy");
                        Date d = null;
                        try {
                            d = formatter.parse(i.getString("date"));
                        } catch (ParseException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
 
                        message.setDate(d);
                        message.setEndDestination(i.getString("end_dest"));
                        message.setName(i.getString("name"));
                        message.setStartDestination(i.getString("strt_loc"));
                        Log.i("time", i.getString("time"));
                        message.setTime(i.getString("time"));
                        Log.i("time_msg", message.getTime());
                        List.add(message);
                        Log.i("list", Integer.toString(List.size()));
                    }
                } else {
                    Log.d("objects", "Error: " + e.getMessage());
                }
 
            }
 
        });
        Log.i("here", "here");
        this.setListAdapter(new ListAdapter(this, List));
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.carpool, menu);
        return true;
    }
 
    // on refereshing
    @Override
    public void onRefreshStarted(View view) {
        // TODO Auto-generated method stub
        get();
        new AsyncTask<Void, Void, Void>() {
 
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Thread.sleep(5000);
                    Log.i("sleep", "asynced sleep");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }
 
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
 
                // Notify PullToRefreshAttacher that the refresh has finished
                mPullToRefreshAttacher.setRefreshComplete();
            }
        }.execute();
 
    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        SmsFormat sms = (SmsFormat) getListAdapter().getItem(position);
         Log.i("MSG", "hi");
        // use this sms item....
        Toast.makeText(getApplicationContext(), sms.getTime(),
                Toast.LENGTH_LONG).show();
    }
 
}

Screenshot_2013-12-07-11-56-09

Screenshot_2013-12-07-11-56-16

advertisement

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.