آموزش قرار دادن محتوای json در spinner در اندروید
سلام دوستان در این سری از آموزش برنامه نویسی اندروید به آموزش قرار دادن محتوای json در spinner در اندروید می پردازیم در این آموزش ابتدا یک json را از یک url می خوانیم سپس دیتای به دست آماده را در Spinner قرار خواهیم داد و زمانی که کاربر یکی از آیتم های Spinner را انتخاب کند یکسری داده جدید در به دست خواهند آماد در ادامه با ما همراه باشید.
در ابتدای کار باید یک کتاب خانه را به پروژه خود اضافه کنید.
وارد فایل Build.gradle از نوع Module شده و در بخش dependencies خط زیر را اضافه کنید.
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
سپس پروژه را sync کنید.
فایل json ما در آدرس زیر قرار دارد.
http://orjinakteb.com/api/spinner_json.php
برای اینکه از کتاب خانه های سمت Netwrok استفاده نکنیم و باعث بالا نرفتن حجم برنامه شویم از کتاب خانه سفارشی خودمان برای دانلود و پارس json استفاده خواهیم کرد.
یک فایل جاوا به نام JSONfunctions.java ایجاد کرده و کدهای زیر را در آن قرار دهید.
package ir.programchi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
با استفاده از کد بالا می توانیم json را از url دریافت کنیم و آن را پارس (parse) یا همان تجزیه کنیم.
بعد از اینکار وارد layout خود شده در اینجا نام آن برابر با activity_main.xml است و کدهای زیر را در آن قرار دهید.
<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" >
<Spinner
android:id="@+id/my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/my_spinner" />
<TextView
android:id="@+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rank" />
<TextView
android:id="@+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/country" />
</RelativeLayout>
در بالا یکسری TextView و یک Spinner در نظر گرفته شده است.
یادتان نرود در بخش AndroidManifest.xml دسترسی زیر را اضافه کنید.
<uses-permission android:name="android.permission.INTERNET" />
و در آخر وارد فایل MainActivity.java شده و کدهای زیر را در آن قرار دهید.
package com.androidbegin.jsonspinnertutorial;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<WorldPopulation> world;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL("http://orjinakteb.com/api/spinner_json.php");
try {
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
بیشتر کار در کلاس Async انجام می شود این کلاس را قبلا توضیح داده بودیم که کارش چی بوده در سایت واژه async را جستجو کنید و بعد از اینکه فایل json دانلود شد مقدایر را دریافت شده و در spinner قرار خواهد گرفت و با انتخاب هر spinner یکسری داده جدید در textView ها قرار می گیرد.
این آموزش هم به پایان رسید.
موفق و پیروز باشید.
آموزش برنامه نویسی اندروید |
ممنون از اموزش خوب شما
واقعا تکید
خواهش می کنم موفق باشید.