Make an HTTP request with android

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

http://www.stoimen.com/blog/wp-content/uploads/2011/04/http.jpg

If you want make an HTTP request, We had recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

Now in your Activity you must make call resquest in onCreate:

new RequestTask().execute("http://stackoverflow.com");

Download code

How to read and write JSON from file with Gson

You can save JSON when you call web service. You must use the same methods which was used last item.

When you read this JSON, you must use Gson library.

http://howtodoinjava.com/wp-content/uploads/2014/06/google-gson.jpg
Download Gson Library.

public void returnJSONToYourModel() {
		final String json = Utils.readFromFile(MainActivity.this);
		final Gson gson = new Gson();
		final YourModel yourModel = gson.fromJson(json, YourModel.class);

	}

Download code.

How to read and write from file

JSON

It’s very esay to read and write from a file.

Download code

public static void writeToFile(String data, Activity activity) {
		try {
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					activity.openFileOutput("config.txt", Context.MODE_PRIVATE));
			outputStreamWriter.write(data);
			outputStreamWriter.close();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
		}
	}

	public static String readFromFile(Activity activity) {

		String ret = "";

		try {
			InputStream inputStream = activity.openFileInput("config.txt");

			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();
			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}
		 return ret;
	}

How to use Retrofit library

Retrofit parse JSON of your web service. Use Retrofit library is very simple

Retrofit turns your REST API into a Java interface.

you can download this example from here

You need these librarires.

JSON

Then you can get your JSON, We use this chrome app. Now you can build your model from JSON in this web

You create a new class which name is RestClient

package com.thedeveloperworldisyours.simpleretrofic.webservice;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.OkClient;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;
import android.os.Handler;
import android.util.Log;

import com.squareup.okhttp.OkHttpClient;
import com.thedeveloperworldisyours.simpleretrofic.model.Question;
import com.thedeveloperworldisyours.simpleretrofic.utils.Constants;

public class RestClient {

	public interface ClientInterface{
		  @GET("/questions")
		  void getQuestions( @Query("sort") String sort, @Query("site") String site,@Query("pagesize") String pagesize,@Query("page") String page, Callback<Question> callback);
		}

	public static ClientInterface initRestAdapter()
    {
        OkHttpClient client = new OkHttpClient();

        return (ClientInterface) new RestAdapter.Builder()
                .setClient(new OkClient(client))
                .setEndpoint(Constants.URL)
                .build()
                .create(ClientInterface.class);
    }
	public static void GetQuestions(final Handler mHandler) {
		Callback<Question> callback = new Callback<Question>() {

			@Override
			public void failure(RetrofitError resp) {
				Log.v("failure", String.valueOf(resp.getMessage()));
			}

			@Override
			public void success(Question info, Response resp) {
				Log.v("success", String.valueOf(resp.getStatus()));
			}
		};
		RestClient.initRestAdapter().getQuestions(Constants.SORT, Constants.SITE,
				Constants.PAGESIZE, Constants.PAGE, callback);
	}

}

Now in your MainActivity put this:

package com.thedeveloperworldisyours.simpleretrofic;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.thedeveloperworldisyours.simpleretrofic.model.Question;
import com.thedeveloperworldisyours.simpleretrofic.utils.Constants;
import com.thedeveloperworldisyours.simpleretrofic.utils.Utils;
import com.thedeveloperworldisyours.simpleretrofic.webservice.RestClient;

public class MainActivity extends ActionBarActivity {

	List<String> mListTitle = new ArrayList<String>();
	private ListView mListView;

		protected ListView getListView() {
		    if (mListView == null) {
		        mListView = (ListView) findViewById(android.R.id.list);
		    }
		    return mListView;
		}

		protected void setListAdapter(ListAdapter adapter) {
		    getListView().setAdapter(adapter);
		}

		protected ListAdapter getListAdapter() {
		    ListAdapter adapter = getListView().getAdapter();
		    if (adapter instanceof HeaderViewListAdapter) {
		        return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
		    } else {
		        return adapter;
		    }
		}

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.activity_main);
		getQuestionCheckInternet();

	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);
        return true;
    }
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

        switch (item.getItemId())
        {
        case R.id.action_refresh:
        	refreshList();
        	if(Utils.isOnline(MainActivity.this)){
    			Toast.makeText(this, R.string.action_refresh, Toast.LENGTH_SHORT).show();
    		}
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
        }
	public void refreshList(){
		mListTitle.clear();
		getQuestionCheckInternet();
		createList();

	}

	public void getQuestionCheckInternet(){
		if(Utils.isOnline(MainActivity.this)){
			getQuestions();
		}else{
			Toast.makeText(this, R.string.info_offline, Toast.LENGTH_LONG).show();
		}
	}

	protected void onListItemClick(ListView lv, View v, int position, long id) {
	    getListView().getOnItemClickListener().onItemClick(lv, v, position, id);
	    String item = (String) getListAdapter().getItem(position);
		Toast.makeText(this, item, Toast.LENGTH_LONG).show();
	}

	public void getQuestions() {
		Callback<Question> callback = new Callback<Question>() {

			@Override
			public void failure(RetrofitError resp) {
				Log.v("failure", String.valueOf(resp.getMessage()));
			}

			@Override
			public void success(Question info, Response resp) {
				Log.v("success", String.valueOf(resp.getStatus()));
				getTitle(info);
	            createList();
			}
		};
		RestClient.initRestAdapter().getQuestions(Constants.SORT, Constants.SITE,
				Constants.PAGESIZE, Constants.PAGE, callback);
	}

	public List<String> getTitle(Question info) {
		for (int i = 0; i < info.getItems().size(); i++) {
			mListTitle.add(info.getItems().get(i).getTitle());
		}
		return mListTitle;
	}
	public void createList(){

		// use your custom layout
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		        android.R.layout.simple_list_item_1,mListTitle);
		setListAdapter(adapter);
	}
}

you can download this example from here

OK – A communication app – I

OK - Communication App LogoI’m glad to announce that our communication app for android: OK has just been released.

OK is a communication app made for lazy people, with the aim of easing the communication. Basically, it allows you customise a predefined list of the messages that you use more often, so that you can use them rather than type them all the time.

Our aim is to let the app learn from each individual usage, and automatically generate a relevant list of messages for each recipient, time and situation. There is still la long way to get there, but we already have the basics in place.

Please, feel free to try out the app and don’t forget to give us some feedback, as we are looking forward to hear peoples thoughts of it.

Enough introduction, this post is the first of a series where we will show you step by step how we built the app, along with all the challenges we faced, and our approaches to solve them.

To begin with, since this is a communication app, we need to display the list of contacts.

In order to do load the contacts we need to do add the following in your AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS" />

Then, create a new method in your activity to fetch all the contacts and put them into a List:

public List<ContactItem> getDataForListView(Context context)
{
    List<ContactItem> contactsList = new ArrayList<ContactItem>();
    Cursor cursor;

    cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    while (cursor.moveToNext()) {
        String contactName = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String storedNumber = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        String phNumber = new String(storedNumber).replace(" ", "");
        int contactID = cursor.getInt(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
        ContactItem contact = new ContactItem(contactName, phNumber, contactID);
        contactsList.add(contact);
    }
    cursor.close();

    return contactsList;
}

We use ContactItem which is a custom class to allow us to store the name, id and phone number of the contact. The class is defined as:

public class ContactItem
{

    String name;
    String phone;
    int id;

    public ContactItem(String name, String phone, int id)
    {
        super();
        this.name = name;
        this.phone = phone;
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getPhone()
    {
        return phone;
    }

    public void setPhone(String phone)
    {
        this.phone = phone;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }
}

Now, we have all the contacts into a list, and we can easily display them inside a list view, but first we have to solve the following problem:
We are trying to use the phone number as the unique identifier of the users, but that would only work if they are in international format (including the country code), and unfortunately, there are many contacts that doesn’t have the full number stored in the device.

We needed a mechanism to convert or validate the numbers so that they are all in a standard format, otherwise we wouldn’t have a reliable way to identify the contacts as registered users of the app.

Stay tuned to find out how we solved that problem… and much more!