In this tutorial I’ll provide you with an Android Translation App example program. I’ll use the translation web service I built in parts 4, 5 and 6 of my web services video tutorial. I’ll also show how to parse JSON data in an Android app.
Everything has been kept as easy to make as possible and all of the code follows the video below with many comments.
If you like videos like this, it helps others to find it when you share on Google Plus with a click here [googleplusone]
Code From the Video
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.newthinktank.derekbanas.translation" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MyActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
activity_my.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Translate" android:id="@+id/button" android:layout_below="@+id/editText" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:onClick="onTranslateClick"/> <TextView android:id="@+id/translationTextView" android:text="@string/translation_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="94dp" /> </RelativeLayout> |
MyActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
package com.newthinktank.derekbanas.translation; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; public class MyActivity extends Activity { EditText translateEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } // Calls for the AsyncTask to execute when the translate button is clicked public void onTranslateClick(View view) { EditText translateEditText = (EditText) findViewById(R.id.editText); // If the user entered words to translate then get the JSON data if(!isEmpty(translateEditText)){ Toast.makeText(this, "Getting Translations", Toast.LENGTH_LONG).show(); // Calls for the method doInBackground to execute new SaveTheFeed().execute(); } else { // Post an error message if they didn't enter words Toast.makeText(this, "Enter Words to Translate", Toast.LENGTH_SHORT).show(); } } // Check if the user entered words to translate // Returns false if not empty protected boolean isEmpty(EditText editText){ // Get the text in the EditText convert it into a string, delete whitespace // and check length return editText.getText().toString().trim().length() == 0; } // Allows you to perform background operations without locking up the user interface // until they are finished // The void part is stating that it doesn't receive parameters, it doesn't monitor progress // and it won't pass a result to onPostExecute class SaveTheFeed extends AsyncTask<Void, Void, Void>{ // Holds JSON data in String format String jsonString = ""; // Will hold the translations that will be displayed on the screen String result = ""; // Everything that should execute in the background goes here // You cannot edit the user interface from this method @Override protected Void doInBackground(Void... voids) { // Get access to the EditText so we can get the text in it EditText translateEditText = (EditText) findViewById(R.id.editText); // Get the text from EditText String wordsToTranslate = translateEditText.getText().toString(); // Replace spaces in the String that was entered with + so they can be passed // in a URL wordsToTranslate = wordsToTranslate.replace(" ", "+"); // Client used to grab data from a provided URL DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); // Provide the URL for the post request HttpPost httpPost = new HttpPost("http://newjustin.com/translateit.php?action=translations&english_words=" + wordsToTranslate); // Define that the data expected is in JSON format httpPost.setHeader("Content-type", "application/json"); // Allows you to input a stream of bytes from the URL InputStream inputStream = null; try{ // The client calls for the post request to execute and sends the results back HttpResponse response = httpClient.execute(httpPost); // Holds the message sent by the response HttpEntity entity = response.getEntity(); // Get the content sent inputStream = entity.getContent(); // A BufferedReader is used because it is efficient // The InputStreamReader converts the bytes into characters // My JSON data is UTF-8 so I read that encoding // 8 defines the input buffer size BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); // Storing each line of data in a StringBuilder StringBuilder sb = new StringBuilder(); String line = null; // readLine reads all characters up to a \n and then stores them while((line = reader.readLine()) != null){ sb.append(line + "\n"); } // Save the results in a String jsonString = sb.toString(); // Create a JSONObject by passing the JSON data JSONObject jObject = new JSONObject(jsonString); // Get the Array named translations that contains all the translations JSONArray jArray = jObject.getJSONArray("translations"); // Cycles through every translation in the array outputTranslations(jArray); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } // Called after doInBackground finishes executing @Override protected void onPostExecute(Void aVoid) { // Put the translations in the TextView TextView translationTextView = (TextView) findViewById(R.id.translationTextView); translationTextView.setText(result); } protected void outputTranslations(JSONArray jsonArray){ // Used to get the translation using a key String[] languages = {"arabic", "chinese", "danish", "dutch", "french", "german", "italian", "portuguese", "russian", "spanish"}; // Save all the translations by getting them with the key try{ for(int i = 0; i < jsonArray.length(); i++){ JSONObject translationObject = jsonArray.getJSONObject(i); result = result + languages[i] + " : " + translationObject.getString(languages[i]) + "\n"; } } catch (JSONException e) { e.printStackTrace(); } } } } |
strings.xml
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Translation</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="translation_text_view">Enter words above for translation</string> </resources> |
Hi I am getting an error with new SaveTheFeed.execute(); execute is throwing a ‘cannot resolve execute’ error. Any pointers?
nvm I resolved this, I was not invoking the class with ()
Glad you fixed it. Sorry I couldn’t help sooner
How can i do it with google translate?
I found the JSON file in there: and replace your example but nothing in the TextView. Please help me.
You have to pay for the Google translate API. There is a limited version of the API for free however.
Oh! I didn’t know that. Thank you so much. 🙂
You’re very welcome 🙂