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