Android에서 새로운 기능, JSON 데이터에서 listview를 만들려고합니다.Android "스크립트가 예외를받을 때 알림을 표시하는 방법"
스크립트가 예외 처리 될 때 사용자에게 경고를 표시 할 수 없다는 점을 제외하면 모든 것이 정상입니다.
내 목표는 JSON을 얻기 위해 서버에 요청하기 전에 인터넷 연결을 먼저 청취하는 것입니다. 연결이없는 경우 앱은 사용자에게 인터넷 연결을 켜라는 경고를 표시합니다.
현재 인터넷에 연결되어 있지 않으면 응용 프로그램이 강제로 대화 상자를 닫고 응용 프로그램을 닫습니다.
public class HargaActivity extends ListActivity {
//SET URL
private static String url = "http://www.jualanmotor.com/JmApi/DaftarMotor/?username=elis&password=puspasarikeisha";
// JSON Node names
private static final String TAG_data = "data";
private static final String TAG_Parent = "Parent";
private static final String TAG_Parent_name = "parent_name";
private static final String TAG_Category = "Category";
private static final String TAG_Category_name = "category_name";
private static final String TAG_product_title = "product_title";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> productList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.harga_layout);
new ProgressTask(HargaActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean>
{
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
this.dialog.setMessage("Trying get content");
this.dialog.show();
}
protected void onPostExecute(final Boolean success)
{
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(HargaActivity.this, productList,
R.layout.list_item,
new String[] {TAG_product_title}, new int[] {
R.id.product_title});
setListAdapter(adapter);
dialog.dismiss();
}
@Override
protected Boolean doInBackground(final String... args){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json;
json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_data);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Parent is again JSON Object
JSONObject parent = c.getJSONObject(TAG_Parent);
String parent_name = parent.getString("name");
// Category is again JSON Object
JSONObject category = c.getJSONObject(TAG_Category);
String category_name = category.getString("name");
String product_title = parent_name + "-" + category_name;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Parent_name, product_title);
map.put(TAG_Category_name, category_name);
map.put(TAG_product_title, product_title);
// adding HashList to ArrayList
productList.add(map);
}
return true;
} catch (Exception e) {
/*
**I WANT TO SHOW ALERT MESSAGE HERE**
*/
return false;
}
}
}
}
그리고이 내 JSONParse.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}