ダウンロードしたJSONファイル(GSONで解析)のコンテンツを扱うAndroidアプリを作っています。さて、すべての方法の後にsetContentView()
の後に起こっている、私は思うようにパフォーマンスはあまり良くありません。 最初私のアプリケーション(レイアウト、ビュー)の内容をロードして表示し、を入力し、からJSONをダウンロードします。どうすれば達成できますか?良い例は、FacebookのAndroidアプリです。アプリを実行してからjsonをダウンロードしてください
出典:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xyz);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if(isNetworkAvailable()) {
try {
URL urlLiczba = new URL("https://xyz/");
InputStreamReader readerLiczba = new InputStreamReader(urlLiczba.openStream(/*SK*/));
Gson gson = new Gson();
LiczbaImprez liczbaImprez = gson.fromJson(readerLiczba, LiczbaImprez.class);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = null;
ImageView logo = null;
TextView nazwa = null;
TextView czasMiejsce = null;
String czasMiejsceStr;
TextView opis = null;
LinearLayout lista = (LinearLayout) findViewById(R.id.listaImprez);
for (int i = 0; i < Integer.parseInt(liczbaImprez.liczba); i++) {
URL url = new URL("https://xyz/dir/" + i);
InputStreamReader reader = new InputStreamReader(url.openStream());
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
Imprezy imprezy = gson.fromJson(jsonReader, Imprezy.class);
layout = (LinearLayout) inflater.inflate(R.layout.item_imprezy, null);
logo = (ImageView) layout.findViewById(R.id.ikonaImprezy);
nazwa = (TextView) layout.findViewById(R.id.nazwaImprezy);
czasMiejsce = (TextView) layout.findViewById(R.id.czasMiejsce);
opis = (TextView) layout.findViewById(R.id.opisImprezy);
switch (imprezy.typ) {
case "element1":
logo.setImageResource(R.drawable.logo_of_element1);
break;
case "element2":
logo.setImageResource(R.drawable.logo_of_element2);
break;
default:
break;
}
nazwa.setText(imprezy.nazwa);
czasMiejsceStr = imprezy.data + " - " + imprezy.miejsce;
czasMiejsce.setText(czasMiejsceStr);
opis.setText(imprezy.opis);
lista.addView(layout);
}
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "Something went wrong :/.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
}
}
else{
Toast.makeText(getApplicationContext(), "No connection!", Toast.LENGTH_LONG).show();
}
}
private class LiczbaImprez {
String liczba;
}
private class Imprezy{
String typ;
String nazwa;
String miejsce;
String data;
String opis;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
関連するコードを表示してください。 –
ネットワークコードを 'AsyncTask'に移動する必要があります。 –
私のルートクラスは 'extends' AsyncTask <>ですか? – h3wro