How to get Json object using UrlConnection in android? - android

Hi I am very for android just one week ago I come into this technology and in my app I am integrating services.
Here I have used HttpClient for that, but in android 6 I was deprecated.
That's why we have to use URlconnection, but how can we use this Url connection instead of HttpClient?
My code is below.
Please help me.
my code:-
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}

Use Volley instead. Volley is compatible with almost all APIs.
See here on how to do this.

Related

Update the second spinner based on first spinner item

i have created the two spinner in xml namely myspinner and myspinner1. The myspinner value is obtained from the json value.Based on myspinner item selected,we get the hotel id.That retrieved hotel id is used to call the another AsyncT1.In the AsyncT1 the myspinner1 value get listed out.My problem is,if i select the myspinner the myspinner1 value is not updated it remains same.I have tried the adapter.notifydatasetchanged() but till now not updated.`
class AsyncT extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/hotel");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "response -----" + responseServer);
//Get the instance of JSONArray that contains JSONObjects
// postData(responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("Hotel_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
movie.setHotelid1(jsonObject.optString("hotel_id").toString());
movie.setHotelname1(jsonObject.optString("hotel_name").toString());
hotelNames.add(jsonObject.optString("hotel_name").toString());
movieList.add(movie);
System.out.println("movie list" + movieList);
runOnUiThread(new Runnable() {
#Override
public void run() {
Adapter = (new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, hotelNames));
mySpinner.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
System.out.println("name--"+hotelid);
new AsyncT1().execute(hotelid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
class AsyncT1 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// http://airbnb.abservetech.com/demo/public/mobile/hotelroom/roomid?hotel_id=79
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/show");
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
/*hotel_id&room_type&room_prize&is_active&available_status&adults_count&room_count&room_images&
room_desc&room_name&room_footage&General&Services&Food_Beverages&Outdoors&Activities&
Dining&Media_Entertainment&Kitchen&Others*/
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("hotel_id", hotelid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "viewroomresponse -----" + responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("view_room_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
// movie.setViewRoomtype(jsonObject.optString("room_type").toString());
movie.setViewRoomprice(jsonObject.optString("room_prize").toString());
movie.setViewIsActive(jsonObject.optString("is_active").toString());
movie.setViewAvailablestatus(jsonObject.optString("available_status").toString());
movie.setViewAdultcount(jsonObject.optString("adults_count").toString());
movie.setViewRoomcount(jsonObject.optString("room_count").toString());
movie.setViewRoomdesc(jsonObject.optString("room_desc").toString());
movie.setViewRoomname(jsonObject.optString("room_name").toString());
movie.setViewRoomfootage(jsonObject.optString("room_footage").toString());
RoomNames.add(jsonObject.optString("room_type").toString());
movieList.add(movie);
runOnUiThread(new Runnable() {
#Override
public void run() {
// ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,RoomNames);
// Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Adapter.notifyDataSetChanged();
// mySpinner1.setAdapter(Adapter);
Adapter1 =(new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, RoomNames));
if(Adapter1!=null){
Adapter1.notifyDataSetChanged();
mySpinner1.setAdapter(Adapter1);
}
else{ mySpinner1.setAdapter(Adapter1);}
mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
room_price.setText(movieList.get(position).getViewRoomprice());
description.setText(movieList.get(position).getViewRoomdesc());
adult_count.setText(movieList.get(position).getViewAdultcount());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
`
Use this link, it might help you.
http://www.javaknowledge.info/populate-second-spinner-based-on-selection-of-first-spinner/

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

Restrict doInBackground() to Fetch 30 items at a time to populate Listview using json with EndlessScrollListener

I fetched json from server using asynctask and populated the listview. The list is too large and taking more time in 2g networks. so i want to use endscrolllistener on listview. When ever user scrolled down, it should fetch 30 items at a time. Can anyone please help me how to implement this. how to restrict doInBackground method to fetch only 30 items to listview at a time.
Please look into my code.
public class Articles extends Activity {
ArrayList<ArticlesGetSet> articlesList;
ArticlesAdapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articles_main);
mProgressDialog = new ProgressDialog(Articles.this);
mProgressDialog.setMessage("Currently downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Log.i("Main", "finito onCreate");
articlesList = new ArrayList<ArticlesGetSet>();
new JSONAsyncTask()
.execute("url");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ArticlesAdapter(getApplicationContext(),
R.layout.articles_row, articlesList);
listview.setAdapter(adapter);
listview.setOnScrollListener(new EndlessScrollListener());
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Articles.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("articles");
for (int i = 0; i < 30; i++) {
JSONObject object = jarray.getJSONObject(i);
ArticlesGetSet actor = new ArticlesGetSet();
actor.setName(object.getString("name"));
actor.setDob(object.getString("dob"));
actor.setHeight(object.getString("height"));
articlesList.add(actor);
}
return true;
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
// if (result == false)
// Toast.makeText(getApplicationContext(),
// "Unable to fetch data from server", Toast.LENGTH_LONG)
// .show();
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new LoadMoreTask().execute("url");
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
class LoadMoreTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Articles.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("articles");
for (int i = 30; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
ArticlesGetSet actor = new ArticlesGetSet();
actor.setName(object.getString("name"));
actor.setDob(object.getString("dob"));
actor.setHeight(object.getString("height"));
articlesList.add(actor);
}
return true;
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
}
}
}
Change
for (int i = 30; i < jarray.length(); i++) {
to
for (int i = 0; i < 30 && i < jarray.length(); i++) {

what should be the correct answer for this exception? "Android.os.NetworkOnMainThreadException"

what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});

My app crashes after I use doInBackground(Object... arg0)

Everything was fine until I used doInBackground(Object... arg0) inorder to show ProgressDialog until it is loaded then dismisses it on onPostExecute(Object result) method. No error message in a LogCat, just crashes. Please help?
Vacancy.java
package com.apps.vacancy;
//all the necessary imports are imported
public class Vacancy extends Activity {
public static String urlPageNumHolder;
public ProgressDialog dialog;
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchJob();
}
});
}
public void searchJob() {
new LoadContentFromServer().execute();
dialog = ProgressDialog.show(this, "Vacancy", "Loading...", true, false);
}
public String getJSONUrl(String url, List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... arg0) {
String url = "http://10.0.2.2/android/smartaddis/mobile/vacancy/getVacancy.php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", inputText.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url, params));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("title_en", c.getString("title_en"));
map.put("description_en", c.getString("description_en"));
map.put("posteddate", c.getString("posteddate"));
map.put("expiredate", c.getString("expiredate"));
MyArrList.add(map);
}
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView,
int position, long mylng) {
urlPageNumHolder = MyArrList.get(position).get("id").toString();
Intent subActivity = new Intent(Vacancy.this,
VacancyWebber.class);
Bundle translateBundle = ActivityOptions
.makeCustomAnimation(Vacancy.this,
R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
startActivity(subActivity, translateBundle);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return MyArrList;
}
#Override
protected void onPostExecute (ArrayList<HashMap<String, String>> result) {
if (dialog != null)
dialog.dismiss();
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
}
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
You are updating ui from doInbackground which you should not do. Return the result in doInbackground and update ui in onPostExecute.
In doInbackground return MyArrList. The result of background computation is a passed to onPostExecute.
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... params) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
... // rest of the code
return MyArrList;
}
In onPostExecute initialize adapter and set the adapter to listview.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// dimiss dialog
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
... // rest of the code
}
For more info
http://developer.android.com/reference/android/os/AsyncTask.html
You also need to move the below inside onCreate after setContentView coz findViewById looks for a view in the current inflated layout.
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);

Categories

Resources