app crashes when no internet connected - android

i am trying to get data from server, when i disable internet it gives error. my Activitycode is
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hos);
new ProgressTask(Hospital.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", 5).show();
startActivity(new Intent(Hospital.this, MainActivity.class));
}
}
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, contact },
new int[] { R.id.vehicleType, R.id.vehicleColor });
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> map = (HashMap<String, String>) lv
.getItemAtPosition(position);
String name = map.get("name");
Intent intent = new Intent(Hospital.this,
DataViewActivity.class);
intent.putExtra("itemName", name);
startActivity(intent);
}
});
}
protected Boolean doInBackground(final String... args) {
baseAdapter jParser = new baseAdapter();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vcolor = c.getString(contact);
String vfuel = c.getString(Category);
// String vtread = c.getString(TREAD);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(contact, vcolor);
map.put(Category, vfuel);
// map.put(TREAD, vtread);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
baseAdapter:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
logcat:
08-16 12:36:00.271: E/JSON Parser(17005): Error parsing data org.json.JSONException: End of input at character 0 of
08-16 12:36:00.271: W/dalvikvm(17005): threadid=11: thread exiting with uncaught exception (group=0x40a7f228)
08-16 12:36:00.281: E/AndroidRuntime(17005): FATAL EXCEPTION: AsyncTask #1
08-16 12:36:00.281: E/AndroidRuntime(17005): java.lang.RuntimeException: An error occured while executing doInBackground()
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.lang.Thread.run(Thread.java:864)
08-16 12:36:00.281: E/AndroidRuntime(17005): Caused by: java.lang.NullPointerException
08-16 12:36:00.281: E/AndroidRuntime(17005): at com.example.careandcure.Hospital$ProgressTask.doInBackground(Hospital.java:124)
08-16 12:36:00.281: E/AndroidRuntime(17005): at com.example.careandcure.Hospital$ProgressTask.doInBackground(Hospital.java:1)
08-16 12:36:00.281: E/AndroidRuntime(17005): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-16 12:36:00.281: E/AndroidRuntime(17005): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-16 12:36:00.281: E/AndroidRuntime(17005):
my question is when i connect the internet it works fine but when i disconnect it crashes the app and also shows toast not internet connection

if you don't have a internet connection following line return null to you:
jParser.getJSONFromUrl(url);
so json is null in your code and you can't run following code:
for (int i = 0; i < json.length(); i++)
for solving this issue you can check json that is not null
if (json != null)
{
// your code
}

Your code is written assuming the attempt to get the json will work and be valid. If you have no internet connection it will timeout instead. In that case json will be null. You need to check for that case and handle it.

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

Fatal exception #asynk task

i'm a new Andorid noob :) ... and my first question on SO :)
So what i want to do:
I use a button to login with Facebook, i receive the GraphUser and i call a service to register the user with his facebook data in database.
The register is done in Asynk task.
I receive the json from service and on onPostExecute I want to make another call to other service with the database userId that i received from json,
also in an asynk task to get other data an then populate the view.
Here is where i get the asynk task exception on doInBackground. I've done someting wrong?
Here is the call for register with his facebook data:
public class GetUserFacebookDataTask extends AsyncTask<Void, Void, String> {
Activity activity;
String fbNameParam;
String fbEmailParam;
String passwordParam = "";
String android_id = "";
String fbGengerParam;
public GetUserFacebookDataTask(String fbNameParam, String fbEmailParam,
final Activity current_activity, String android_id,
String fbGengerParam) {
this.activity = current_activity;
this.fbNameParam = fbNameParam;
this.fbEmailParam = fbEmailParam;
this.android_id = android_id;
this.fbGengerParam = fbGengerParam;
}
#Override
protected String doInBackground(Void... params) {
Log.d("GetUserFacebookDataTask doInBackground",
"GetUserFacebookDataTask");
Map<String, Object> paramsSend = new LinkedHashMap<String, Object>();
paramsSend.put("name", fbNameParam);
paramsSend.put("email", fbEmailParam);
paramsSend.put("password", "");
paramsSend.put("deviceToken", android_id);
paramsSend.put("deviceType", 2);
paramsSend.put("withFacebook", 1);
if (fbGengerParam.equals("male")) {
fbGengerParam = "m";
} else {
fbGengerParam = "f";
}
paramsSend.put("gender", fbGengerParam);
String stausHandler = null;
JsonObject response = null;
try {
response = WebServiceApi.PostToServiceLoginFacebook("login",
paramsSend);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
if (response != null) {
JsonObject jsonData = ((JsonObject) response.get("userData"));
JsonElement userPhotoUrl = jsonData.get("userPhotoUrl");
JsonElement userPhoto = jsonData.get("userPhoto");
JsonElement userNewEmail = jsonData.get("userNewEmail");
JsonElement userAge = jsonData.get("userAge");
String userPhotoUrlf = "";
String userPhotof = "";
String userNewEmailf = "";
String userAgef = "";
if (userPhotoUrl.toString().equals("null")) {
userPhotoUrlf = "-";
}
if (userPhoto.toString().equals("null")) {
userPhotof = "-";
}
if (userNewEmail.toString().equals("null")) {
userNewEmailf = "-";
}
if (userAge.toString().equals("null")) {
userAgef = "-";
}
UserData userData = new UserData(userPhotoUrlf, jsonData.get(
"userHeightInterval").toString(), jsonData.get(
"userCity").toString(), userPhotof, jsonData.get(
"userPassword").toString(), jsonData.get("userStyle")
.toString(), jsonData.get("userEmail").toString(),
jsonData.get("userDateRegistered").toString(), jsonData
.get("userConfirmed").toString(), jsonData.get(
"userWithFacebook").toString(), jsonData.get(
"userID").toString(), jsonData
.get("userGender").toString(), jsonData.get(
"userWantsPushNotifications").toString(),
jsonData.get("userName").toString(), userNewEmailf,
userAgef, jsonData.get("userShape").toString());
UserData data = AppManager.getInstance().setUserData(userData);
if (userData != null) {
JsonElement status = response.get("status");
stausHandler = status.toString();
}
}
return stausHandler;
}
protected void onPostExecute(String status) {
Log.d("GetUserFacebookDataTask onPostExecute",
"GetUserFacebookDataTask onPostExecute");
StatusHandlerLoginFb(status.toString(), activity);
}
}
//status handler from the json received
public void StatusHandlerLoginFb(String status, Activity currentActivity) {
if (status.equals("0")) {
Log.d("StatusHandlerLoginFb", "StatusHandlerLoginFb");
Intent intent = new Intent(currentActivity,
NavigationActivity.class);
currentActivity.startActivity(intent);
//new GetPhotoDataTaskFb(currentActivity).execute();
new GetPhotoDataTask(currentActivity).execute();
}
}
// the other task
public class GetPhotoDataTask extends
AsyncTask> {
Activity activity;
public GetPhotoDataTask(Activity activity) {
this.activity = activity;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
Log.d("GetPhotoDataTask onPreExecute", "GetPhotoDataTask onPreExecute");
super.onPreExecute();
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
#Override
protected List<PhotoData> doInBackground(Void... params) {
Log.d("GetPhotoDataTask doInBackground", "GetPhotoDataTask doInBackground");
MyStyleApi myStyleApi = new MyStyleApi();
List<PhotoData> photoData = null;
try {
photoData = myStyleApi.getPhotoDataWithDispatch();
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> photoStr = new ArrayList<String>();
for (int i = 0; i < photoData.size(); i++) {
photoStr.add(photoData.get(i).getPhotoURL());
}
String[] photoUrls = new String[photoStr.size()];
photoUrls = photoStr.toArray(photoUrls);
AppManager.getInstance().setphotoUrls(photoUrls);
List<PhotoData> photoDataS = AppManager.getInstance().setPhotoData(
photoData);
return photoData;
}
protected void onProgressUpdate(Integer... percent) {
progressDialog = ProgressDialog.show(activity, "Preluare Date",
"Va rugam asteptati!");
}
protected void onPostExecute(List<PhotoData> photoData) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
//getPhotoDataWithDispatch and the other method to receive data
// get PhotoData with userId as param
public List<PhotoData> getPhotoDataWithDispatch() throws JSONException,
ClientProtocolException, IOException {
Log.d("getPhotoDataWithDispatch ", "getPhotoDataWithDispatch ");
UserData data = AppManager.getInstance().getUserData();
final String userID = data.getUserID();
Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("userID", userID);
JsonArray response = WebServiceApi.PostToServiceWithStringResponse(
"images/get_images_data", params);
if (response != null) {
List<PhotoData> photoDataList = new ArrayList<PhotoData>();
photoDataList = parseJsonArrayForFotoData(response);
return photoDataList;
}
return null;
}
// the log cat
06-01 14:44:27.400: D/getUserDataFacebookLogin2(24790): getUserDataFacebookLogin2
06-01 14:44:27.410: D/GetUserFacebookDataTask doInBackground(24790): GetUserFacebookDataTask
06-01 14:44:27.410: D/PostToServiceLoginFacebook(24790): PostToServiceLoginFacebook
06-01 14:44:27.940: D/GetUserFacebookDataTask onPostExecute(24790): GetUserFacebookDataTask onPostExecute
06-01 14:44:27.940: D/StatusHandlerLoginFb(24790): StatusHandlerLoginFb
06-01 14:44:27.980: D/GetPhotoDataTask onPreExecute(24790): GetPhotoDataTask onPreExecute
06-01 14:44:28.040: D/GetPhotoDataTask doInBackground(24790): GetPhotoDataTask doInBackground
06-01 14:44:28.040: D/getPhotoDataWithDispatch(24790): getPhotoDataWithDispatch
06-01 14:44:28.070: D/memalloc(24790): /dev/pmem: Mapped buffer base:0x4ddae000 size:8110080 offset:7618560 fd:66
06-01 14:44:28.190: W/dalvikvm(24790): threadid=13: thread exiting with uncaught exception (group=0x40c541f8)
06-01 14:44:28.200: E/AndroidRuntime(24790): FATAL EXCEPTION: AsyncTask #3
06-01 14:44:28.200: E/AndroidRuntime(24790): java.lang.RuntimeException: An error occured while executing doInBackground()
06-01 14:44:28.200: E/AndroidRuntime(24790): at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-01 14:44:28.200: E/AndroidRuntime(24790): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.lang.Thread.run(Thread.java:856)
06-01 14:44:28.200: E/AndroidRuntime(24790): Caused by: java.lang.IllegalStateException: This is not a JSON Array.
06-01 14:44:28.200: E/AndroidRuntime(24790): at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
06-01 14:44:28.200: E/AndroidRuntime(24790): at com.example.palashfashion.webservice.WebServiceApi.PostToServiceWithStringResponse(WebServiceApi.java:166)
06-01 14:44:28.200: E/AndroidRuntime(24790): at com.example.palashfashion.webservice.MyStyleApi.getPhotoDataWithDispatch(MyStyleApi.java:97)
06-01 14:44:28.200: E/AndroidRuntime(24790): at com.example.palashfashion.webservice.MyStyleApi$GetPhotoDataTask.doInBackground(MyStyleApi.java:877)
06-01 14:44:28.200: E/AndroidRuntime(24790): at com.example.palashfashion.webservice.MyStyleApi$GetPhotoDataTask.doInBackground(MyStyleApi.java:1)
06-01 14:44:28.200: E/AndroidRuntime(24790): at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-01 14:44:28.200: E/AndroidRuntime(24790): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-01 14:44:28.200: E/AndroidRuntime(24790): ... 5 more
The reason it's crashing is because WebServiceApi.PostToServiceWithStringResponse is not returning a Json array

Json parsing:Service handling Exception in 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();
}

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.

AsyncTask progress loader json list not working

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

Categories

Resources