Android включает в себя библиотеки json.org, которые позволяют легко работать с JSON-файлами.
В этом примере мы разберём, как происходит чтение JSON и его разбор. Напишем простейший твиттер-клиент.
В начале подготовительные работы. Добавьте в ваш файл «main.xml» многострочное текстовое поле:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/twitter_messages" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="false" android:text="@string/twitter_messages" /> </LinearLayout> |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/twitter_messages" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="false" android:text="@string/twitter_messages" /> </LinearLayout>
И не забудьте также про файл ресурсов «strings.xml», куда нужно внести строку, связанную с нашим текстовым полем.
1 2 3 4 5 6 | <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Twitter</string> <string name="twitter_messages"></string> </resources> |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Twitter</string> <string name="twitter_messages"></string> </resources>
Всё. На этом подготовительные работы закончены. Приступаем к основной части. Создайте новый Android-проект «twitter.com.com».
Добавьте нижеприведённый код для вашего activity. Он выполняет следующие функции: загружает ленту твиттера для пользователя http://twitter.com/vogella и отображает её содержимое в текстовом поле.
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 | package twitter.com.com; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.widget.TextView; public class TwitterActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { StrictMode.enableDefaults(); super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView twitterMessages = (TextView)findViewById(R.id.twitter_messages); String readTwitterFeed = readTwitterFeed(); StringBuilder messages = new StringBuilder(); try { JSONArray jsonArray = new JSONArray(readTwitterFeed); for (int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); messages.append(jsonObject.getString("text")+'\n'); } twitterMessages.setText(messages.toString()); } catch (Exception e) { e.printStackTrace(); } } public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode ==200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TwitterActivity.class.toString(), "Download fail"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } } |
package twitter.com.com; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.widget.TextView; public class TwitterActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { StrictMode.enableDefaults(); super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView twitterMessages = (TextView)findViewById(R.id.twitter_messages); String readTwitterFeed = readTwitterFeed(); StringBuilder messages = new StringBuilder(); try { JSONArray jsonArray = new JSONArray(readTwitterFeed); for (int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); messages.append(jsonObject.getString("text")+'\n'); } twitterMessages.setText(messages.toString()); } catch (Exception e) { e.printStackTrace(); } } public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode ==200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TwitterActivity.class.toString(), "Download fail"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } }
Для запуска этого примера нужно в файле "AndroidManifest.xml" дать права приложению для доступа в интернет (android.permission.INTERNET). Я приведу свой вариант AndroidManifest.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="twitter.com.com" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".TwitterActivity" 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> |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="twitter.com.com" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".TwitterActivity" 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>
Исходные тексты проекта можно скачать по ссылке: twitter
Пост написан по мотивам статьи: http://www.vogella.de/articles/AndroidJSON/article.html.
О том, как лучше обращаться с базами данных, по мнению компании Microsoft, вы можете прочитать на сайте coding4.net - использование LINQ to Objects, LINQ to XML, LINQ to SQL