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
Related
An error occurred while executing doinBackground().
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddComment.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
//postData("deepika");
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String post_title = intime.getText().toString();
String post_message = outtime.getText().toString();
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(AddComment.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("intime", post_title));
params.add(new BasicNameValuePair("outtime", post_message));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL, "POST",
params);
//JSONObject json1 = jsonParser.makeHttpRequest("http://192.168.10.30/webservice/comments.php", "POST",
// params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Attendence Marked!", json.toString());
//finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Attendence Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
finish();
if (file_url != null) {
Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
This is the error log:
11-05 05:03:20.171: E/AndroidRuntime(3171): FATAL EXCEPTION: AsyncTask #1
11-05 05:03:20.171: E/AndroidRuntime(3171): Process: com.example.mysqltest, PID: 3171
11-05 05:03:20.171: E/AndroidRuntime(3171): java.lang.RuntimeException: An error occurred while executing doInBackground()
11-05 05:03:20.171: E/AndroidRuntime(3171): at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-05 05:03:20.171: E/AndroidRuntime(3171): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-05 05:03:20.171: E/AndroidRuntime(3171): at java.lang.Thread.run(Thread.java:841)
11-05 05:03:20.171: E/AndroidRuntime(3171): Caused by: java.lang.NullPointerException
in click listener do this
mSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vw) {
String post_title = intime.getText().toString();
String post_message = outtime.getText().toString();
new PostComment(post_title,post_message).execute();
}
});
and in the asynch task change this
class PostComment extends AsyncTask<String, String, String> {
String response = "";
String post_title ="";
String post_message="";
// Check for success tag
int success;
public PostComment(String title,String msg) {
post_title = title;
post_message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddComment.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
//postData("deepika");
}
#Override
protected String doInBackground(String... args) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(AddComment.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("intime", post_title));
params.add(new BasicNameValuePair("outtime", post_message));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL, "POST",
params);
//JSONObject json1 = jsonParser.makeHttpRequest("http://192.168.10.30/webservice/comments.php", "POST",
// params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Attendence Marked!", json.toString());
response = json.getString(TAG_MESSAGE);
}else{
Log.d("Attendence Failure!", json.getString(TAG_MESSAGE));
response = json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
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.
I have been feching datas from url.Depending on first url,second will works and depending on the second third will work.I have been set all datas into spinner when i modify the first spinner the other two spinner modifies and shows an error.
03-28 11:17:38.958: D/dalvikvm(659): GC_FOR_MALLOC freed 8320 objects / 625048 bytes in 63ms
03-28 11:17:38.958: E/AndroidRuntime(659): FATAL EXCEPTION: AsyncTask #2
03-28 11:17:38.958: E/AndroidRuntime(659): java.lang.RuntimeException: An error occured while executing doInBackground()
03-28 11:17:38.958: E/AndroidRuntime(659): at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.lang.Thread.run(Thread.java:1096)
03-28 11:17:38.958: E/AndroidRuntime(659): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 59: http://192.169.11.175/AndroidService/Restful.svc/getarea/80 Feet Road
03-28 11:17:38.958: E/AndroidRuntime(659): at java.net.URI.create(URI.java:970)
03-28 11:17:38.958: E/AndroidRuntime(659): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.ServiceHandler.makeServiceCall(ServiceHandler.java:67)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.ServiceHandler.makeServiceCall(ServiceHandler.java:33)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.HomeActivity$GetArea.doInBackground(HomeActivity.java:192)
03-28 11:17:38.958: E/AndroidRuntime(659): at com.example.testspinner.HomeActivity$GetArea.doInBackground(HomeActivity.java:1)
03-28 11:17:38.958: E/AndroidRuntime(659): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-28 11:17:38.958: E/AndroidRuntime(659): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-28 11:17:38.958: E/AndroidRuntime(659): ... 4 more
HomeActivity.class
public class HomeActivity extends Activity {
private static String state_url = "/AndroidService/restful.svc/GetState/";
private static String city_url = "/AndroidService/restful.svc/Getcity/";
private static String city_area = "/AndroidService/Restful.svc/getarea/";
Spinner sp_state,sp_city,sp_area,sp_pin;
ArrayList<String> state_name,state_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sp_state = (Spinner)findViewById(R.id.spinner_state);
sp_area = (Spinner)findViewById(R.id.spinner_area);
sp_city = (Spinner)findViewById(R.id.spinner_city);
sp_pin = (Spinner)findViewById(R.id.spinner_pin);
new GetState(HomeActivity.this).execute();
sp_state.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3)
{
String item = sp_state.getSelectedItem().toString();
if(!item.equals("select"))
{
new GetCity(HomeActivity.this, state_id.get(pos)).execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp_city.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
// TODO Auto-generated method stub
String name = sp_city.getItemAtPosition(pos).toString();
if(!name.equals("select"))
{
new GetArea(HomeActivity.this, name).execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
class GetState extends AsyncTask<Void, Void, Void>
{
Context con;
public GetState(Context c)
{
this.con = c;
}
#Override
protected Void doInBackground(Void... params)
{
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(state_url, ServiceHandler.GET);
if(jsonStr!=null)
{
try
{
state_name = new ArrayList<String>();
state_id = new ArrayList<String>();
state_name.add("select");
state_id.add("select");
JSONArray ary = new JSONArray(jsonStr);
for(int i=0;i<ary.length();i++)
{
String name = ary.getJSONObject(i).getString("StateName");
int city_id = ary.getJSONObject(i).getInt("PkId");
state_name.add(name);
state_id.add(""+city_id);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, state_name);
sp_state.setAdapter(state_Adapter);
}
}
class GetCity extends AsyncTask<Void, Void, Void>
{
Context con;
String state_id;
ArrayList<String> mycity;
public GetCity(Context c,String id) {
this.con = c;
this.state_id = id;
}
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(city_url+""+state_id, ServiceHandler.GET);
if(jsonStr!=null)
{
try
{
JSONArray myary = new JSONArray(jsonStr);
mycity = new ArrayList<String>();
mycity.add("select");
for(int i=0;i<myary.length();i++)
{
String city = myary.getJSONObject(i).getString("City");
mycity.add(city);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, mycity);
sp_city.setAdapter(state_Adapter);
}
}
class GetArea extends AsyncTask<Void, Void, Void>
{
Context con;
String name;
ArrayList<String> myarea;
public GetArea(Context c,String name) {
this.con = c;
this.name = name;
}
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(city_area+""+name, ServiceHandler.GET);
Log.d("CityResponse: ", "> " + jsonStr);
if(jsonStr!=null)
{
try
{
JSONArray myary = new JSONArray(jsonStr);
myarea = new ArrayList<String>();
myarea.add("select");
for(int i=0;i<myary.length();i++)
{
String city = myary.getJSONObject(i).getString("Area");
Log.d("city", city);
myarea.add(city);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<String> state_Adapter = new ArrayAdapter<String>(con, R.layout.custom_layout, R.id.textView_custom, myarea);
sp_area.setAdapter(state_Adapter);
}
}
}
ServiceHandler.class
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
Try this..
You can see your url from logcat like this
/AndroidService/Restful.svc/getarea/80 Feet Road
from that you can see 80 Feet Road there is space between them
space need to replace with %20 use below method to use your url URLEncoder
You can use the java.net.URLEncoder to encode the URL as in
import java.net.URLEncoder;
String uu;
try {
uu = URLEncoder.encode(yoururl,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
when my application try to display the searched result, the application was closed like this:http://i.imgur.com/YPl4Bfw.jpg?1
here is the information showed in logcat
E/Buffer Error(784): Error converting result java.lang.NullPointerException: lock == null
E/JSON Parser(784): Error parsing data org.json.JSONException: End of input at character 0 of
W/dalvikvm(784): threadid=15: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(784): FATAL EXCEPTION: AsyncTask #4
E/AndroidRuntime(784): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(784): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(784): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(784): at
java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(784): at
java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(784): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(784): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(784): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(784): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(784): Caused by: java.lang.NullPointerException
E/AndroidRuntime(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.doInBackground(SearchResultDisplay.java:82)
E/AndroidRuntime(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.doInBackground(SearchResultDisplay.java:1)
E/AndroidRuntime(784): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(784): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(784): ... 4 more
11-23 14:24:49.267: W/EGL_emulation(784): eglSurfaceAttrib not implemented
E/WindowManager(784): Activity com.example.qrandrary.SearchResultDisplay has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40dec338 V.E..... R......D 0,0-470,144} that was originally added here
E/WindowManager(784): android.view.WindowLeaked: Activity com.example.qrandrary.SearchResultDisplay has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40dec338 V.E..... R......D 0,0-470,144} that was originally added here
E/WindowManager(784): at android.view.ViewRootImpl.(ViewRootImpl.java:354)
E/WindowManager(784): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
E/WindowManager(784): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(784): at android.app.Dialog.show(Dialog.java:281)
E/WindowManager(784): at com.example.qrandrary.SearchResultDisplay$LoadAllBooks.onPreExecute(SearchResultDisplay.java:68)
E/WindowManager(784): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(784): at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(784): at com.example.qrandrary.SearchResultDisplay.onCreate(SearchResultDisplay.java:53)
E/WindowManager(784): at android.app.Activity.performCreate(Activity.java:5104)
E/WindowManager(784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
E/WindowManager(784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
E/WindowManager(784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/WindowManager(784): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/WindowManager(784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/WindowManager(784): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(784): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(784): at a
ndroid.app.ActivityThread.main(ActivityThread.java:5041)
E/WindowManager(784): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(784): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/WindowManager(784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/WindowManager(784): at dalvik.system.NativeStart.main(Native Method)
here is the code:
public class SearchResultDisplay extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> booksList;
// url to get all products list
private static String url_all_books = "http://127.0.0.1/qrandrary/quickSearch.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BOOKS = "books";
private static final String TAG_BID = "bid";
private static final String TAG_BNAME = "bname";
private static final String TAG_AUTHORS = "authors";
private static final String TAG_STATUS = "status";
private static final String TAG_PUBLISHER = "publisher";
ListView listView;
List<RowItem> rowItems;
// products JSONArray
JSONArray books = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_resultlist_view);
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(android.R.id.list);
new LoadAllBooks().execute();
}
class LoadAllBooks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchResultDisplay.this);
pDialog.setMessage("Loading Books. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Bundle extras = getIntent().getExtras();
String keyword = extras.getString("keyword");
url_all_books = url_all_books + "?keyword=" + keyword;
JSONObject json = jParser.makeHttpRequest(url_all_books, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Books: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
books = json.getJSONArray(TAG_BOOKS);
// looping through All Products
for (int i = 0; i < books.length(); i++) {
JSONObject c = books.getJSONObject(i);
// Storing each json item in variable
String bid = c.getString(TAG_BID);
String bName = c.getString(TAG_BNAME);
String authors = c.getString(TAG_AUTHORS);
String publisher = c.getString(TAG_PUBLISHER);
String status = c.getString(TAG_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_BID, bid);
map.put(TAG_BNAME, bName);
map.put(TAG_AUTHORS, authors);
map.put(TAG_PUBLISHER, publisher);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
booksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
BookListViewAdapter adapter = new BookListViewAdapter(SearchResultDisplay.this,R.layout.search_result_item, rowItems);
listView.setAdapter(adapter);
}
});
}
}
}
public class BookListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public BookListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtBid;
TextView txtBname;
TextView txtAuthors;
TextView txtPublisher;
TextView txtStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.search_result_item, null);
holder = new ViewHolder();
holder.txtBid = (TextView) convertView.findViewById(R.id.bid);
holder.txtBname = (TextView) convertView.findViewById(R.id.bName);
holder.txtAuthors = (TextView) convertView.findViewById(R.id.authors);
holder.txtPublisher = (TextView) convertView.findViewById(R.id.publisher);
holder.txtStatus = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtBid.setText(rowItem.getbId());
holder.txtBname.setText(rowItem.getbName());
holder.txtAuthors.setText(rowItem.getAuthors());
holder.txtPublisher.setText(rowItem.getPublisher());
holder.txtStatus.setText(rowItem.getStatus());
return convertView;
}
}
public class RowItem {
private int bId;
private String bName;
private String authors;
private String status;
private String publisher;
public RowItem(int bId, String bName, String authors, String status,
String publisher) {
this.bId = bId;
this.bName = bName;
this.authors = authors;
this.status = status;
this.publisher = publisher;
}
public int getbId() {
return bId;
}
public void setbId(int bId) {
this.bId = bId;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
What is the problem in my application?
I think what problem in JSON that receives your application. You could check log to find out what isn't correct in JSON object.
I am stuck on this stack trace, I don't know what is reason behind it .
06-27 17:05:14.841: W/SingleClientConnManager(1519): Invalid use of SingleClientConnManager: connection still allocated.
06-27 17:05:14.841: W/SingleClientConnManager(1519): Make sure to release the connection before allocating another one.
06-27 17:05:15.031: E/log_tag(1519): Error in http connection java.net.SocketException: Socket closed
06-27 17:05:15.077: E/log_tag(1519): Error converting result java.lang.NullPointerException
06-27 17:05:15.181: E/log_tag(1519): Error parsing data org.json.JSONException: End of input at character 0 of
06-27 17:05:15.531: W/dalvikvm(1519): threadid=10: thread exiting with uncaught exception (group=0x40014760)
06-27 17:05:15.821: E/AndroidRuntime(1519): FATAL EXCEPTION: AsyncTask #2
06-27 17:05:15.821: E/AndroidRuntime(1519): java.lang.RuntimeException: An error occured while executing doInBackground()
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$3.done(AsyncTask.java:266)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.lang.Thread.run(Thread.java:1020)
06-27 17:05:15.821: E/AndroidRuntime(1519): Caused by: java.lang.NullPointerException
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:87)
06-27 17:05:15.821: E/AndroidRuntime(1519): at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:1)
06-27 17:05:15.821: E/AndroidRuntime(1519): at android.os.AsyncTask$2.call(AsyncTask.java:252)
06-27 17:05:15.821: E/AndroidRuntime(1519): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-27 17:05:15.821: E/AndroidRuntime(1519): ... 4 more
There are two json responses work at the same time in different activities. If I run single Response above Null pointer error does not affect on my output.
First activity contain tabhost (Tab) . First tab(default tab) has another async task.
This is my first activity wich contain Json call and Tab host.
public class Login_Header extends TabActivity
{
Button Find;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
//To show Custom Title as image
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.login_header_bar);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_about_tab);
// Font size has been changed through Styles.xml for tab
TabHost tabHost = getTabHost();
Intent feeds = new Intent(this,Feeds.class);
tabHost.addTab(tabHost.newTabSpec("Tab1")
.setIndicator("Feeds")
.setContent(feeds));
Intent challenges = new Intent(this,Challenges.class);
tabHost.addTab(tabHost.newTabSpec("Tab2")
.setIndicator("Challenges")
.setContent(challenges));
Intent friends = new Intent(this,Friends.class);
tabHost.addTab(tabHost.newTabSpec("Tab3")
.setIndicator("Friends")
.setContent(friends));
Intent group = new Intent(this,Groups.class);
tabHost.addTab(tabHost.newTabSpec("Tab4")
.setIndicator("Groups")
.setContent(group));
Intent details = new Intent(this,Details.class);
tabHost.addTab(tabHost.newTabSpec("Tab5")
.setIndicator("Details")
.setContent(details));
tabHost.setCurrentTab(0);
Find.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent find = new Intent(Login_Header.this,Find.class);
startActivity(find);
}
});
//To call async task
callNotificationCount();
}
private void callNotificationCount()
{
new NotificationCount_Async().execute("");
}
private class NotificationCount_Async extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
try
{
URL url=new URL(getString(R.string.WebServiceURL)+"/notifications/notificationcount");
HttpPost httppost = new HttpPost(url.toString());
HttpResponse responsePOST = LoginPage.httpClient.execute(httppost);
HttpEntity resEntity = responsePOST.getEntity();
InputStream instream = resEntity.getContent();
String result = convertStreamToString(instream);
Log.i("User Feed",result);
return result;
}
catch(Exception ex)
{
Log.e("error", "error", ex);
return null;
}
}
#Override
protected void onPostExecute(String result)
{
try {
JSONObject json = new JSONObject(result);
//Below code is for user count
JSONObject userNotificationjson = json.getJSONObject("user_notification");
if(json.has("user_notification"))
{
String userCount = userNotificationjson.getString("count");
int Count = Integer.parseInt(userCount);
if(Count > 0)
{
LinearLayout llUserCount = (LinearLayout)findViewById(R.id.llUserCount);
TextView userCountTextView =(TextView)findViewById(R.id.txtUserCount);
llUserCount.setVisibility(View.VISIBLE);
userCountTextView.setText(userCount);
}
}
}
private String convertStreamToString(InputStream is)
{
//code
}
Now this is my second activity , Default Tab activity which again have json request.
public class Feeds extends Activity
{
SessionManager session;
String custom_phpsess_id,logged_in_id_User,returnString;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String FIRST_NAME = "firstname";
static String LAST_NAME = "lastname";
static String ACTION = "action";
// static String ACTIVITY_NAME = "activity_name";
static String IMAGE_URL = "image";
static String USER_ID = "user_id";
static String ACTIVITY_NAME = "activityname";
String strUrl = =new URL(getString(R.string.WebServiceURL)+"/users/userfeeds";
ListView mListView;
String id_User;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the view from feeds.xml
setContentView(R.layout.feeds);
session = new SessionManager(getApplicationContext());
//To get values from session
HashMap<String, String> User = session.getUserDetails();
logged_in_id_User = User.get(SessionManager.KEY_ID);
custom_phpsess_id = User.get(SessionManager.KEY_USE);
// Creating a new non-ui thread task to download json data
// Execute DownloadJSON AsyncTask
Log.i("On Create", "Main On Create");
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
Log.i("On DownloadJSON", "onPreExecute");
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Feeds.this);
// Set progressdialog title
mProgressDialog.setTitle("");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
Log.i("On doInBackground", "doInBackground");
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL(strUrl);
Log.i("On doInBackground-jsonObject", jsonobject.toString());
try
{
// Locate the array name
jsonarray = jsonobject.getJSONArray("userdata");
Log.i("On doInBackground-jsonarray", jsonarray.toString());
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
if(jsonobject.getString("actions").equals("Completed"))
{
map.put("firstname", jsonobject.getString("first_name"));
map.put("lastname", jsonobject.getString("last_name"));
map.put("action", jsonobject.getString("actions"));
map.put("image", jsonobject.getString("file_name"));
map.put("user_id", jsonobject.getString("id_user"));
map.put("activityname", jsonobject.getString("activity_name"));
Log.i("On doInBackground-Map", map.toString());
// Set the JSON Objects into the array
arraylist.add(map);
}
}
}
catch (JSONException e)
{
Log.i("On doInBackground-JSONException", e.toString());
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
Log.i("On onPostExecute", "ON post exe");
// Locate the listview in listview_main.xml
listview = (ListView)findViewById(R.id.listview);
Log.i("On onPostExecute-onPostExecute-arraylist", arraylist.toString());
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(Feeds.this, arraylist);
Log.i("On onPostExecute-onPostExecute-Adapter", adapter.toString());
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
and null pointer line is ..
Line no. 97 is = Log.i("On doInBackground-jsonObject", jsonobject.toString());