Related
I have a problem with refreshing data on the screen, app get the data through JSON everything works fine, but now I need to do the refresh button in the menu. I built my application according to an example. As I understand it does good idea to use SimpleAdapter and need to write a custom adapter. Can you help me please?
ServiceHandler
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
MainActivity
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "******";
// JSON Node names
private static final String TAG_ZLECENIA = "zlecenia";
private static final String TAG_ID = "id";
private static final String TAG_CO = "co";
private static final String TAG_KYDA = "kyda";
private static final String TAG_ILE = "ile";
private static final String TAG_LIM = "lim_czas";
// zlecenia JSONArray
JSONArray zlecenia = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> ZleceniaList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ZleceniaList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String co = ((TextView) view.findViewById(R.id.co))
.getText().toString();
String kyda = ((TextView) view.findViewById(R.id.kyda))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
zlecenia = jsonObj.getJSONArray(TAG_ZLECENIA);
// looping through All Contacts
for (int i = 0; i < zlecenia.length(); i++) {
JSONObject c = zlecenia.getJSONObject(i);
String id = c.getString(TAG_ID);
String co = c.getString(TAG_CO);
String kyda = c.getString(TAG_KYDA);
String ile = c.getString(TAG_ILE);
String lim = c.getString(TAG_LIM);
// tmp hashmap for single contact
HashMap<String, String> zlecenia = new HashMap<String, String>();
// adding each child node to HashMap key => value
zlecenia.put(TAG_ID, id);
zlecenia.put(TAG_CO, co);
zlecenia.put(TAG_KYDA, kyda);
zlecenia.put(TAG_ILE, ile);
zlecenia.put(TAG_LIM, lim);
// adding contact to contact list
ZleceniaList.add(zlecenia);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, ZleceniaList, R.layout.list_item,
new String[] { TAG_KYDA, TAG_CO, TAG_ILE, TAG_LIM,},
new int[] { R.id.kyda, R.id.co, R.id.ile, R.id.lim });
setListAdapter(adapter);
}
}
}
rest/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item
android:id="#+id/action_refresh"
android:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_refresh_white_36dp"
/>
</menu>
You have to override the onOptionsItemSelected() method and handle the refresh menu item click action.
i create chain spinner that get data from server and return it by json. my firts spinner is fine. in second spinner the json give response but when try to save the renspone in array the asynctask error caused by nullpointerexception. when i check it in log cat there is no null in my json response. so i try to change name of array with same name as first spinner there is no error but the second spinner show same value as first spinner.
my question why my second spinner when name of array different from first spinner is error ?
where is the nullpointerexception error because when i check it there is no null ? how to fixed it ?
there is my LoginActivity.java
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ArrayList<Category> categoriesListKota;
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
categoriesList = new ArrayList<Category>();
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new GetKota().execute();
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Log.e("Response Kota: ", "> " + catObj.getString("id_kota"));
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
my category.java
private String id;
private String name;
public Category(){}
public Category(String id, String name){
this.id = id;
this.name = name;
}
public void setId(String id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public String getName(){
return this.name;
}
my serviceHandler.java
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
This is Logcat error:
02-05 18:20:48.953: E/Response:(29903): > {"lokasi":[{"id_provinsi":"1","nama":"Bali"},{"id_provinsi":"2","nama":"Banten"},{"id_provinsi":"3","nama":"Bengkulu"},{"id_provinsi":"4","nama":"DI Yogyakarta"},{"id_provinsi":"5","nama":"DKI Jakarta"},{"id_provinsi":"6","nama":"Gorontalo"},{"id_provinsi":"7","nama":"Irian Jaya Barat"},{"id_provinsi":"8","nama":"Jambi"},{"id_provinsi":"9","nama":"Jawa Barat"},{"id_provinsi":"10","nama":"Jawa Tengah"},{"id_provinsi":"11","nama":"Jawa Timur"},{"id_provinsi":"12","nama":"Kalimantan Barat"},{"id_provinsi":"13","nama":"Kalimantan Selatan"},{"id_provinsi":"14","nama":"Kalimantan Tengah"},{"id_provinsi":"15","nama":"Kalimantan Timur"},{"id_provinsi":"16","nama":"Kep. Bangka Belitung"},{"id_provinsi":"17","nama":"Kep. Riau"},{"id_provinsi":"18","nama":"Lampung"},{"id_provinsi":"19","nama":"Maluku"},{"id_provinsi":"20","nama":"Maluku Utara"},{"id_provinsi":"21","nama":"Nanggroe Aceh Darussalaam"},{"id_provinsi":"22","nama":"Nusa Tenggara Barat"},{"id_provinsi":"23","nama":"Nusa Tenggara Timur"},{"id_provinsi":"24","nama":"Papua"},{"id_provinsi":"25","nama":"Riau"},{"id_provinsi":"26","nama":"Sulawesi Selatan"},{"id_provinsi":"27","nama":"Sulawesi Tengah"},{"id_provinsi":"28","nama":"Sulawesi Tenggara"},{"id_provinsi":"29","nama":"Sulawesi Utara"},{"id_provinsi":"30","nama":"Sumatra Barat"},{"id_provinsi":"31","nama":"Sumatra Selatan"},{"id_provinsi":"32","nama":"Sumatra Utara"}]}
02-05 18:20:49.573: E/Response:(29903): > {"lokasi":[{"id_kota":"1","id_provinsi":"1","nama":"KABUPATEN BADUNG"},{"id_kota":"2","id_provinsi":"1","nama":"KABUPATEN BANGLI"},{"id_kota":"3","id_provinsi":"1","nama":"KABUPATEN BULELENG"},{"id_kota":"4","id_provinsi":"1","nama":"KABUPATEN GIANYAR"},{"id_kota":"5","id_provinsi":"1","nama":"KABUPATEN JEMBRANA"},{"id_kota":"6","id_provinsi":"1","nama":"KABUPATEN KARANG ASEM"},{"id_kota":"7","id_provinsi":"1","nama":"KABUPATEN KLUNGKUNG"},{"id_kota":"8","id_provinsi":"1","nama":"KABUPATEN TABANAN"},{"id_kota":"9","id_provinsi":"1","nama":"KOTA DENPASAR"}]}
02-05 18:20:49.573: E/Response Kota:(29903): > 1
02-05 18:20:49.573: W/dalvikvm(29903): threadid=16: thread exiting with uncaught exception (group=0x415b1360)
02-05 18:20:49.603: E/AndroidRuntime(29903): FATAL EXCEPTION: AsyncTask #2
02-05 18:20:49.603: E/AndroidRuntime(29903): java.lang.RuntimeException: An error occured while executing doInBackground()
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$3.done(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.lang.Thread.run(Thread.java:856)
02-05 18:20:49.603: E/AndroidRuntime(29903): Caused by: java.lang.NullPointerException
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:377)
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:1)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$2.call(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-05 18:20:49.603: E/AndroidRuntime(29903): ... 5 more
please help me thanks. sorry i dont know how to post logcat
Try to change these code:
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
to:
private static final String KEY_LOGIN = "login";
private static final String URL_LOGIN = "http://api.omidev.com/login/format/json";
private static final String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
See the difference. The second using static final. Then, change void to String while using String parameter. For example:
private class Login extends AsyncTask<String, Void, Void> {
// Change void to String if the first AsyncTask parameter is a String.
// If the first parameter is Void, change to void (in lowercase)
#Override
protected String doInBackground(String... arg) { // Must be a String type, because the first parameter type is a String.
Sorry my fault. i already fixed my code
in GetKota Asynctask i did not initialized categoriesListKota, so that make it error caused by nullpointerexception.
to make the second spinning change when selected value from first spinning i add notifyDataSetChanged() to change the spinner adapter on populateSpinnerKota() and clear() on GetKota Asynctask to make the spinner clean from previous data.
this is the correct code for LoginActivity.java
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList = new ArrayList<Category>();
private ArrayList<Category> categoriesListKota = new ArrayList<Category>();
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
spinnerAdapter.notifyDataSetChanged();
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
categoriesListKota.clear();
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
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);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
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;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}
what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(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;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}