Json parsing:Service handling Exception in Android - android

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();
}

Related

Asynctask error while inserting records into phpmyadmin

I have been trying to insert values into database, but on click of button the app crashes. I got two asynctask classes. Is it because of that? any help or tutorial link would be great! the code is below
public class DataEntry extends Activity implements OnItemSelectedListener {
EditText edt_name,edt_age;
RadioGroup gendergroup;
RadioButton radioGenderButton;
Spinner spnr_currentAilment;
Spinner spnr_pastAilment;
Spinner spnr_Place,spnr_Area;
ArrayList<CurrentAilment> c_ailmentList;
ArrayList<getArea> arealist;
ArrayList<getPlace> placelist;
Button btn_submit;
String name,age,gender,current_ailment,past_ailment,place,area;
ProgressDialog pDialog;
// Url to get all the current ailments
private String URL = "http://192.168.0.105/colg_project/health_project.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry);
/* ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
*/
edt_name = (EditText)findViewById(R.id.editName);
edt_age = (EditText)findViewById(R.id.editAge);
gendergroup = (RadioGroup)findViewById(R.id.radioGroupGender);
spnr_currentAilment = (Spinner)findViewById(R.id.spinnerCurrentAilment);
spnr_pastAilment = (Spinner)findViewById(R.id.spinnerPastAilment);
spnr_Place = (Spinner)findViewById(R.id.spinnerPlaceName);
spnr_Area = (Spinner)findViewById(R.id.spinnerAreName);
btn_submit = (Button)findViewById(R.id.btn_Submit);
c_ailmentList = new ArrayList<CurrentAilment>();
new GetInformation().execute();
// spinner item select listener
spnr_currentAilment.setOnItemSelectedListener(this);
spnr_Place.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
// TODO Auto-generated method stub
List<String> area_array = new ArrayList<String>();
for(int j=0;j<arealist.size();j++){
if(placelist.get(position).getPlaceId().equals(arealist.get(j).getPlaceId()) ){
area_array.add(arealist.get(j).getAreaName());
//Log.e("","spiner1"+arealist.get(j).getAreaName());
}
}
ArrayAdapter<String> adapter_area = new ArrayAdapter<String>(DataEntry.this,
android.R.layout.simple_spinner_item, area_array);
adapter_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spnr_Area.setAdapter(adapter_area);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
name = edt_name.getText().toString();
age = edt_age.getText().toString();
radioGenderButton = (RadioButton) findViewById(gendergroup.getCheckedRadioButtonId());
gender = radioGenderButton.getText().toString();
// Log.e("","" + gender);
Toast.makeText(getApplicationContext(), "" + gender, Toast.LENGTH_SHORT).show();
current_ailment = spnr_currentAilment.getSelectedItem().toString();
past_ailment = spnr_pastAilment.getSelectedItem().toString();
place = spnr_Place.getSelectedItem().toString();
area = spnr_Area.getSelectedItem().toString();
insertToDatabase(name,age,gender,current_ailment,past_ailment,place,area);
}
});
}
private void populateSpinner() {
List<String> ailments_array = new ArrayList<String>();
for (int i = 0; i < c_ailmentList.size(); i++) {
ailments_array.add(c_ailmentList.get(i).getCurrent_ailment());
}
// Creating adapter for spinner
ArrayAdapter<String> adapter_ailment = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, ailments_array);
adapter_ailment.setDropDownViewResource(R.layout.spinner_item);
spnr_currentAilment.setAdapter(adapter_ailment);
spnr_pastAilment.setAdapter(adapter_ailment);
//for places spinner
List<String> place_array = new ArrayList<String>();
for(int i = 0;i < placelist.size();i++)
{
place_array.add(placelist.get(i).getPlaceName());
}
ArrayAdapter<String> adapter_places = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,place_array);
adapter_places.setDropDownViewResource(R.layout.spinner_item);
spnr_Place.setAdapter(adapter_places);
}
private class GetInformation extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DataEntry.this);
pDialog.setMessage("loading..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL, ServiceHandler.GET);
placelist = new ArrayList<getPlace>();
arealist = new ArrayList<getArea>();
// Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray ailments = jsonObj.getJSONArray("ailments");
JSONArray places = jsonObj.getJSONArray("places");
JSONArray areas = jsonObj.getJSONArray("areas");
for (int i = 0; i < ailments.length(); i++) {
JSONObject c_ailObj = (JSONObject) ailments.get(i);
CurrentAilment ail = new CurrentAilment();
ail.setId(Integer.parseInt(c_ailObj.getString("id")));
ail.setCurrent_ailment(c_ailObj.getString("ca_name"));
c_ailmentList.add(ail);
}
for (int i = 0; i < places.length(); i++) {
JSONObject place_obj = (JSONObject) places.get(i);
getPlace get_place = new getPlace();
get_place.setPlaceId(place_obj.getString("place_id"));
get_place.setPlaceName(place_obj.getString("place_name"));
placelist.add(get_place);
}
for (int i = 0; i < areas.length(); i++) {
JSONObject area_obj = (JSONObject) areas.get(i);
getArea get_area = new getArea();
get_area.setAreaId(area_obj.getString("area_id"));
get_area.setAreaName(area_obj.getString("area_name"));
get_area.setPlaceId(area_obj.getString("place_id"));
arealist.add(get_area);
}
}
} 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);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private void insertToDatabase(String name, String age,String gender,String c_ailment,String p_ailment,String place,String area){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = edt_name.getText().toString();
String age = edt_age.getText().toString();
radioGenderButton = (RadioButton) findViewById(gendergroup.getCheckedRadioButtonId());
String gender = radioGenderButton.getText().toString();
// Log.e("","" + gender);
Toast.makeText(getApplicationContext(), "" + gender, Toast.LENGTH_SHORT).show();
String c_ailment = spnr_currentAilment.getSelectedItem().toString();
String p_ailment = spnr_pastAilment.getSelectedItem().toString();
String place = spnr_Place.getSelectedItem().toString();
String area = spnr_Area.getSelectedItem().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("age", age));
nameValuePairs.add(new BasicNameValuePair("gender", gender));
nameValuePairs.add(new BasicNameValuePair("c_ailment", c_ailment));
nameValuePairs.add(new BasicNameValuePair("p_ailment", p_ailment));
nameValuePairs.add(new BasicNameValuePair("place", place));
nameValuePairs.add(new BasicNameValuePair("area", area));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("192.168.0.105/insert_colg_dp.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, age, gender,c_ailment,p_ailment,place,area);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* ((TextView) parent.getChildAt(0)).setTextColor(Color.MAGENTA);
((TextView) parent.getChildAt(0)).setTextSize(12);*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
my php code:
<?php
$con = mysqli_connect("localhost","root","","college_project") or die("Error " . mysqli_error($connection));
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$c_ailment = $_POST['c_ailment'];
$p_ailment = $_POST['p_ailment'];
$place = $_POST['place'];
$area = $_POST['area'];
//Creating an sql query2
$sql = "INSERT INTO records (user_name,age,gender,current_ailment,past_ailment,place,area)
VALUES ('$name','$age','$gender','$c_ailment','$p_ailment','$place','$area')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Success';
}
else{
echo 'Failure';
}
//Closing the database
mysqli_close($con);
?>
and finally the log cat:
06-16 23:45:49.807: E/AndroidRuntime(615): FATAL EXCEPTION: AsyncTask #3
06-16 23:45:49.807: E/AndroidRuntime(615): java.lang.RuntimeException: An error occured while executing doInBackground()
06-16 23:45:49.807: E/AndroidRuntime(615): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-16 23:45:49.807: E/AndroidRuntime(615): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.lang.Thread.run(Thread.java:856)
06-16 23:45:49.807: E/AndroidRuntime(615): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-16 23:45:49.807: E/AndroidRuntime(615): at android.os.Handler.<init>(Handler.java:121)
06-16 23:45:49.807: E/AndroidRuntime(615): at android.widget.Toast$TN.<init>(Toast.java:317)
06-16 23:45:49.807: E/AndroidRuntime(615): at android.widget.Toast.<init>(Toast.java:91)
06-16 23:45:49.807: E/AndroidRuntime(615): at android.widget.Toast.makeText(Toast.java:233)
06-16 23:45:49.807: E/AndroidRuntime(615): at colg.project.healthapp.DataEntry$1SendPostReqAsyncTask.doInBackground(DataEntry.java:220)
06-16 23:45:49.807: E/AndroidRuntime(615): at colg.project.healthapp.DataEntry$1SendPostReqAsyncTask.doInBackground(DataEntry.java:1)
06-16 23:45:49.807: E/AndroidRuntime(615): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-16 23:45:49.807: E/AndroidRuntime(615): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-16 23:45:49.807: E/AndroidRuntime(615): ... 5 more
Seems like you're trying to call any UI widget from doInBackground() method which is not directly possible since AsyncTask is worker thread not UI thread. So you will need to call runOnUiThread() method in your doInBackground() method.
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});

spinner fatalexception: asynctask #2 an error occured while executing doInBackground()

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();
}
}

Error while using ProgressDailog using in AsyncTask

I created Application on parsing XML data.I want to show loading progress dialog.
I created two class on ListActivity(MainClass) and other is Download(Which execute in background using Asyntask).
I using Following code.
public class ListActivity extends Activity implements AsyncResponse {
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
String url = "http://www.moneycontrol.com/rss/MCtopnews.xml";
Download download = new Download();
download.delegate = this;
download.execute(url);
}
/*
* After background task of download and parsing xml ArrayList received from
* background task and send it to arrayAdapterzz
*/
#Override
public void processFinish(ArrayList<NewsItem> listArrayList) {
ListView newsListView;
newsListView = (ListView) findViewById(R.id.listView1);
NewsListAdapter newsListAdapter = new NewsListAdapter(
ListActivity.this, 0, listArrayList);
newsListView.setAdapter(newsListAdapter);
}
}
public class Download extends AsyncTask<String, Integer, ArrayList<NewsItem>> {
public AsyncResponse delegate;
private InputStream mInStream;
private ArrayList<NewsItem> mNewsList;
ListActivity la = new ListActivity();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
la.progressDialog.setMessage("Loading");
la.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
la.progressDialog.setProgress(0);
la.progressDialog.show();
}
#Override
protected ArrayList<NewsItem> doInBackground(String... params) {
String urlstr = params[0];
mInStream = downloadFromlUrl(urlstr);
ParseXml parse = new ParseXml();
try {
mNewsList = parse.parseNewsFeed(mInStream);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mNewsList;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(ArrayList<NewsItem> newsList) {
// send back parsed data to ListActivity
delegate.processFinish(newsList);
}
private InputStream downloadFromlUrl(String urlstr) {
try {
URL url = new URL(urlstr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(10 * 1000);
connection.setRequestMethod("GET");
connection.connect();
int response = connection.getResponseCode();
Log.d("debug", "The response is: " + response);
mInStream = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mInStream;
}
}
I am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rss/com.parse.ui.ListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException
at com.parse.net.Download.onPreExecute(Download.java:33)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at com.parse.ui.ListActivity.onCreate(ListActivity.java:30)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more 08-05 06:08:02.113: I/Process(1852): Sending signal. PID: 1852 SIG: 9
It may not be the answer but a concept. You don't need to add ProgressDialog in ListActivity.
public ProgressDialog progressDialog;
and no need to instantiate it here.
Because you want to show the progress of the AsycTask Do it like this
public class ArticleTask extends AsyncTask<String, Void, JSONObject> {
Activity context;
ListView list_of_article;
public ProgressDialog progressDialog;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
public ArticleTask(Activity coontext, ListView listview) {
this.context = coontext;
this.list_of_article = listview;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(context,
"", "");
}
#Override
protected JSONObject doInBackground(String... params)
{
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]); //url
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", array.getJSONObject(x).getString("title"));
map.put("previewimage", array.getJSONObject(x).getString("previewimage"));
map.put("publishdate", array.getJSONObject(x).getString("publishdate"));
map.put("pagetext", array.getJSONObject(x).getString("pagetext"));
map.put("total_comments", array.getJSONObject(x).getString("total_comments"));
map.put("viewcount", array.getJSONObject(x).getString("viewcount"));
map.put("associatedthreadid", array.getJSONObject(x).getString("associatedthreadid"));
list.add(map);
}
ArticleAdapter adapter = new ArticleAdapter(context, list);
list_of_article.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
Remove ProgressDialog from ListActivity and show it on PreExecute and remove/dismiss it on PostExecute.
Try this in your preExecute() method
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(this_context, "Loading",
"Please wait for a moment...");
}

android: The apps was closed when displaying the searched result in listView

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.

java.lang.RuntimeException error occured while executing doInBackground()

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.

Categories

Resources