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();
}
}
I have been feching datas from url.Depending on first url,second will works and depending on the second third will work.I have been set all datas into spinner when i modify the first spinner the other two spinner modifies and shows an error.
03-28 11:17:38.958: D/dalvikvm(659): GC_FOR_MALLOC freed 8320 objects / 625048 bytes in 63ms
03-28 11:17:38.958: E/AndroidRuntime(659): FATAL EXCEPTION: AsyncTask #2
03-28 11:17:38.958: E/AndroidRuntime(659): java.lang.RuntimeException: An error occured while executing doInBackground()
03-28 11:17:38.958: E/AndroidRuntime(659): at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.lang.Thread.run(Thread.java:1096)
03-28 11:17:38.958: E/AndroidRuntime(659): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 59: http://192.169.11.175/AndroidService/Restful.svc/getarea/80 Feet Road
03-28 11:17:38.958: E/AndroidRuntime(659): at java.net.URI.create(URI.java:970)
03-28 11:17:38.958: E/AndroidRuntime(659): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.ServiceHandler.makeServiceCall(ServiceHandler.java:67)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.ServiceHandler.makeServiceCall(ServiceHandler.java:33)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.HomeActivity$GetArea.doInBackground(HomeActivity.java:192)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.HomeActivity$GetArea.doInBackground(HomeActivity.java:1)
03-28 11:17:38.958: E/AndroidRuntime(659): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-28 11:17:38.958: E/AndroidRuntime(659): ... 4 more
HomeActivity.class
public class HomeActivity extends Activity {
private static String state_url = "/AndroidService/restful.svc/GetState/";
private static String city_url = "/AndroidService/restful.svc/Getcity/";
private static String city_area = "/AndroidService/Restful.svc/getarea/";
Spinner sp_state,sp_city,sp_area,sp_pin;
ArrayList<String> state_name,state_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sp_state = (Spinner)findViewById(R.id.spinner_state);
sp_area = (Spinner)findViewById(R.id.spinner_area);
sp_city = (Spinner)findViewById(R.id.spinner_city);
sp_pin = (Spinner)findViewById(R.id.spinner_pin);
new GetState(HomeActivity.this).execute();
sp_state.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3)
{
String item = sp_state.getSelectedItem().toString();
if(!item.equals("select"))
{
new GetCity(HomeActivity.this, state_id.get(pos)).execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp_city.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
// TODO Auto-generated method stub
String name = sp_city.getItemAtPosition(pos).toString();
if(!name.equals("select"))
{
new GetArea(HomeActivity.this, name).execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
class GetState extends AsyncTask<Void, Void, Void>
{
Context con;
public GetState(Context c)
{
this.con = c;
}
#Override
protected Void doInBackground(Void... params)
{
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(state_url, ServiceHandler.GET);
if(jsonStr!=null)
{
try
{
state_name = new ArrayList<String>();
state_id = new ArrayList<String>();
state_name.add("select");
state_id.add("select");
JSONArray ary = new JSONArray(jsonStr);
for(int i=0;i<ary.length();i++)
{
String name = ary.getJSONObject(i).getString("StateName");
int city_id = ary.getJSONObject(i).getInt("PkId");
state_name.add(name);
state_id.add(""+city_id);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, state_name);
sp_state.setAdapter(state_Adapter);
}
}
class GetCity extends AsyncTask<Void, Void, Void>
{
Context con;
String state_id;
ArrayList<String> mycity;
public GetCity(Context c,String id) {
this.con = c;
this.state_id = id;
}
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(city_url+""+state_id, ServiceHandler.GET);
if(jsonStr!=null)
{
try
{
JSONArray myary = new JSONArray(jsonStr);
mycity = new ArrayList<String>();
mycity.add("select");
for(int i=0;i<myary.length();i++)
{
String city = myary.getJSONObject(i).getString("City");
mycity.add(city);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, mycity);
sp_city.setAdapter(state_Adapter);
}
}
class GetArea extends AsyncTask<Void, Void, Void>
{
Context con;
String name;
ArrayList<String> myarea;
public GetArea(Context c,String name) {
this.con = c;
this.name = name;
}
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(city_area+""+name, ServiceHandler.GET);
Log.d("CityResponse: ", "> " + jsonStr);
if(jsonStr!=null)
{
try
{
JSONArray myary = new JSONArray(jsonStr);
myarea = new ArrayList<String>();
myarea.add("select");
for(int i=0;i<myary.length();i++)
{
String city = myary.getJSONObject(i).getString("Area");
Log.d("city", city);
myarea.add(city);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, myarea);
sp_area.setAdapter(state_Adapter);
}
}
}
ServiceHandler.class
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;
}
}
Try this..
You can see your url from logcat like this
/AndroidService/Restful.svc/getarea/80 Feet Road
from that you can see 80 Feet Road there is space between them
space need to replace with %20 use below method to use your url URLEncoder
You can use the java.net.URLEncoder to encode the URL as in
import java.net.URLEncoder;
String uu;
try {
uu = URLEncoder.encode(yoururl,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
when my application try to display the searched result, the application was closed like this:http://i.imgur.com/YPl4Bfw.jpg?1
here is the information showed in logcat
E/Buffer Error(784): Error converting result java.lang.NullPointerException: lock == null
E/JSON Parser(784): Error parsing data org.json.JSONException: End of input at character 0 of
W/dalvikvm(784): threadid=15: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(784): FATAL EXCEPTION: AsyncTask #4
E/AndroidRuntime(784): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(784): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(784): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(784): at
java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(784): at
java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(784): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(784): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(784): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(784): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(784): Caused by: java.lang.NullPointerException
E/AndroidRuntime(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.doInBackground(SearchResultDisplay.java:82)
E/AndroidRuntime(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.doInBackground(SearchResultDisplay.java:1)
E/AndroidRuntime(784): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(784): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(784): ... 4 more
11-23 14:24:49.267: W/EGL_emulation(784): eglSurfaceAttrib not implemented
E/WindowManager(784): Activity com.example.qrandrary.SearchResultDisplay has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40dec338 V.E..... R......D 0,0-470,144} that was originally added here
E/WindowManager(784): android.view.WindowLeaked: Activity com.example.qrandrary.SearchResultDisplay has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40dec338 V.E..... R......D 0,0-470,144} that was originally added here
E/WindowManager(784): at android.view.ViewRootImpl.(ViewRootImpl.java:354)
E/WindowManager(784): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
E/WindowManager(784): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(784): at android.app.Dialog.show(Dialog.java:281)
E/WindowManager(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.onPreExecute(SearchResultDisplay.java:68)
E/WindowManager(784): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(784): at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(784): at com.example.qrandrary.SearchResultDisplay.onCreate(SearchResultDisplay.java:53)
E/WindowManager(784): at android.app.Activity.performCreate(Activity.java:5104)
E/WindowManager(784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
E/WindowManager(784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
E/WindowManager(784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/WindowManager(784): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/WindowManager(784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/WindowManager(784): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(784): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(784): at a
ndroid.app.ActivityThread.main(ActivityThread.java:5041)
E/WindowManager(784): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(784): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/WindowManager(784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/WindowManager(784): at dalvik.system.NativeStart.main(Native Method)
here is the code:
public class SearchResultDisplay extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> booksList;
// url to get all products list
private static String url_all_books = "http://127.0.0.1/qrandrary/quickSearch.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BOOKS = "books";
private static final String TAG_BID = "bid";
private static final String TAG_BNAME = "bname";
private static final String TAG_AUTHORS = "authors";
private static final String TAG_STATUS = "status";
private static final String TAG_PUBLISHER = "publisher";
ListView listView;
List<RowItem> rowItems;
// products JSONArray
JSONArray books = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_resultlist_view);
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(android.R.id.list);
new LoadAllBooks().execute();
}
class LoadAllBooks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchResultDisplay.this);
pDialog.setMessage("Loading Books. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Bundle extras = getIntent().getExtras();
String keyword = extras.getString("keyword");
url_all_books = url_all_books + "?keyword=" + keyword;
JSONObject json = jParser.makeHttpRequest(url_all_books, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Books: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
books = json.getJSONArray(TAG_BOOKS);
// looping through All Products
for (int i = 0; i < books.length(); i++) {
JSONObject c = books.getJSONObject(i);
// Storing each json item in variable
String bid = c.getString(TAG_BID);
String bName = c.getString(TAG_BNAME);
String authors = c.getString(TAG_AUTHORS);
String publisher = c.getString(TAG_PUBLISHER);
String status = c.getString(TAG_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_BID, bid);
map.put(TAG_BNAME, bName);
map.put(TAG_AUTHORS, authors);
map.put(TAG_PUBLISHER, publisher);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
booksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
BookListViewAdapter adapter = new BookListViewAdapter(SearchResultDisplay.this,R.layout.search_result_item, rowItems);
listView.setAdapter(adapter);
}
});
}
}
}
public class BookListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public BookListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtBid;
TextView txtBname;
TextView txtAuthors;
TextView txtPublisher;
TextView txtStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.search_result_item, null);
holder = new ViewHolder();
holder.txtBid = (TextView) convertView.findViewById(R.id.bid);
holder.txtBname = (TextView) convertView.findViewById(R.id.bName);
holder.txtAuthors = (TextView) convertView.findViewById(R.id.authors);
holder.txtPublisher = (TextView) convertView.findViewById(R.id.publisher);
holder.txtStatus = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtBid.setText(rowItem.getbId());
holder.txtBname.setText(rowItem.getbName());
holder.txtAuthors.setText(rowItem.getAuthors());
holder.txtPublisher.setText(rowItem.getPublisher());
holder.txtStatus.setText(rowItem.getStatus());
return convertView;
}
}
public class RowItem {
private int bId;
private String bName;
private String authors;
private String status;
private String publisher;
public RowItem(int bId, String bName, String authors, String status,
String publisher) {
this.bId = bId;
this.bName = bName;
this.authors = authors;
this.status = status;
this.publisher = publisher;
}
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
What is the problem in my application?
I think what problem in JSON that receives your application. You could check log to find out what isn't correct in JSON object.
I beginner in android development, getting error in following code. i am calling asyn method for http request.Its giving me java.lang.RuntimeException error occured while executing doInBackground()
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr = null;
String url=params[0];
System.out.println("fsfsddddf"+params[0]);
ControlDashboard obj = new ControlDashboard();
try{
JSONObject aobj = obj.getJSONFromUrl(url);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
super.onPostExecute(menuitemArr);
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
try {
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
//progressDialog.dismiss();
}
}
Error when i run my android application.
12-17 13:22:48.035: W/dalvikvm(1160): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
12-17 13:22:48.045: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #2
12-17 13:22:48.045: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 13:22:48.045: E/AndroidRuntime(1160): at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-17 13:22:48.045: E/AndroidRuntime(1160): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
json request class:
public class ControlDashboard extends Activity {
public static DefaultHttpClient httpClient;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// 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) {
jObj = null;
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
or
ListView list = (ListView) findViewById(R.id.listView3);
here you are trying to access UI elements from Background Thread means from AsyncTask doInBackground which is not possible
solution move all ui related code in onPostExecute for updating ui after doInBackground complete
you can see here how we update UI from onPostExecute after when doInBackground execution complete
EDIT : or just use this PostAlert AsyncTask class :
private class PostAlert extends AsyncTask<String, Integer, JSONArray>{
private ProgressDialog progressDialog;
#Override
protected JSONArray doInBackground(String... params) {
// TODO Auto-generated method stub
JSONArray menuitemArr=null;
String url=params[0];
System.out.println("fsfsddddf"+url);
// System.out.println("fsfsddddfobj"+obj);
try{
JSONObject aobj = obj.getJSONFromUrl(url);
System.out.println("fsfsf"+aobj);
JSONObject array = aobj.getJSONObject("alert_list");
menuitemArr = array.getJSONArray("array");
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return menuitemArr;
}
#Override
protected void onPostExecute(JSONArray menuitemArr) {
// TODO Auto-generated method stub
if (menuitemArr.length() == 0) {
startActivity(new Intent("com.example.mysampleapp.ABOUT"));
//Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
}else{
name = new String[menuitemArr.length()];
System.out.println("name"+name);
alert = new String[menuitemArr.length()];
date = new String[menuitemArr.length()];
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
name[i] = menuitemArr.getJSONObject(i).getString("name").toString();
alert[i] = menuitemArr.getJSONObject(i).getString("message").toString();
date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
}
ListView list = (ListView) findViewById(R.id.listView3);
ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[] {"col1", "col2", "col3"};
int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
for(int i=0; i<name.length; i++)
{
HashMap<String,String> map = new HashMap<String, String>();
map.put("col1", name[i]);
map.put("col2", alert[i]);
map.put("col3", date[i]);
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
list.setAdapter(arrayAdapter);
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(Alert.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("please wait...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
System.out.println("fsgsgsg");
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressDialog.setProgress(values[0]);
}
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
You are setting ListAdapter in Background which should not be done as it is UI thread task. Change your entire code in doInBackground() to onPostExecute() except for getJsonFromUrl(url). you can return the jsonobject from doInBackground() which you can get in onPostExecute() as result parameter. Still you get that runtime error in onPostExecute() too then you just right this line listview.setAdapter() in
runOnUIThread(new Runnable(){
public void run()
{
}
});
I hope its clear and it will work for you.
Hey i was using the list of friends which gets from the mysql db via php. it sometimes takes a while depends on the connection strenght. so i wanted to use a loader till it gets the data. but im getting errors.
please help me.
thk you,
Code
public class Activity_YourFriendsWith_Class extends Activity {
public String PREFS_NAME = "MyPrefsFile";
public String PREFS_USERID = "prefsUserId";
private static final String TAG_Name = "fname";
private static final String TAG_LName = "lname";
String result = "";
public String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yourfriendswith);
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
userId = pref.getString(PREFS_USERID, "");
Button back = (Button) findViewById(R.id.addback);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(getApplication(), Activity_MyProfile_Class.class);
startActivity(intent);
finish();
}
});
Button addfrnds = (Button) findViewById(R.id.addfrnds);
addfrnds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inti = new Intent();
inti.setClass(Activity_YourFriendsWith_Class.this,
Activity_AddFreinds_Class.class);
startActivity(inti);
}
});
ProgressTask task = new ProgressTask();
task.execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog pd;
private Activity activity;
#Override
protected Boolean doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userId));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://hopscriber.com/friendshopscriber.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
// parse json data
try {
ArrayList<HashMap<String, String>> placelist = new ArrayList<HashMap<String, String>>();
JSONArray jArray = new JSONArray(result);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Name, json_data.getString("fname"));
map.put(TAG_LName, json_data.getString("lname"));
placelist.add(map);
}
}
ListView list = (ListView) findViewById(R.id.frndslist);
ListAdapter adapter = new SimpleAdapter(activity, placelist,
R.layout.listrow_yourfriendswith, new String[] { TAG_Name,
TAG_LName }, new int[] {
R.id.fname, R.id.lname });
list.setAdapter(adapter);
} catch (JSONException e1) {
ListView list = (ListView) findViewById(R.id.frndslist);
list.setEmptyView(findViewById(R.id.fempty));
}
return null;
}
}
}
Logcat
08-16 18:38:17.910: E/AndroidRuntime(452): FATAL EXCEPTION: AsyncTask #1
08-16 18:38:17.910: E/AndroidRuntime(452): java.lang.RuntimeException: An error occured while executing doInBackground()
08-16 18:38:17.910: E/AndroidRuntime(452): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.lang.Thread.run(Thread.java:1019)
08-16 18:38:17.910: E/AndroidRuntime(452): Caused by: java.lang.NullPointerException
08-16 18:38:17.910: E/AndroidRuntime(452): at android.widget.SimpleAdapter.<init>(SimpleAdapter.java:85)
08-16 18:38:17.910: E/AndroidRuntime(452): at hopscriber.com.Activity_YourFriendsWith_Class$ProgressTask.doInBackground(Activity_YourFriendsWith_Class.java:142)
08-16 18:38:17.910: E/AndroidRuntime(452): at hopscriber.com.Activity_YourFriendsWith_Class$ProgressTask.doInBackground(Activity_YourFriendsWith_Class.java:1)
08-16 18:38:17.910: E/AndroidRuntime(452): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-16 18:38:17.910: E/AndroidRuntime(452): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-16 18:38:17.910: E/AndroidRuntime(452): ... 4 more
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private Activity activity;
......
ListAdapter adapter = new SimpleAdapter(activity, ......);
}
Variable activity not defined - so you are get NPE
And also you can't manipulate with your ListView inside method doInBackground. You should do this in onPostExecute method
Try to separating your code into different states, do internet connection stuff in doInbackground(), and manipulate your listview in onPostExecute() to make sure the AsyncTask already done its job
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//load your progressBar here
//for instance
ProgressBar bar = (ProgressBar) findViewById(R.id.yourProgressBar);
bar.setVisibility(View.VISIBLE);
//Load your content here
}
protected void onPostExecute() {
//manipulate your list view here, after fill in some content
//set your loading bar invisible
bar.setVisibility(View.INVISIBLE);
}
}