Related
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.
Outline:
I have to get some operators list from server.
Below is my JSON data
{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}
JSON data has "operator_id" and "operator_name".
I have to get both from url and display only "operator_name" in a spinner.
I Have already implemented the above. Please find the main_activity for reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
plans = (TextView)findViewById(R.id.browseplans);
plans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), BrowsePlans.class);
in.putExtra("operator_id", id_click);
startActivity(in);
}
});
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
currentDateandTime = sdf.format(new Date());
apikey = API_KEY.toString();
currentDateandTime.toString();
codetohash = currentDateandTime + apikey;
SHA1Hash = computeSha1OfString(codetohash);
uri = new Uri.Builder()
.scheme("http")
.authority("xxx.in")
.path("atm")
.appendQueryParameter("op", "GetPrepaidServiceList")
.appendQueryParameter("responseType", "json")
.appendQueryParameter("time", currentDateandTime)
.appendQueryParameter("clientId", ClientId)
.appendQueryParameter("hash", SHA1Hash)
.build();
stringUri = uri.toString();
new DataFromServer().execute();
} //end onCreate()
private class DataFromServer extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
try {
url = new URL(stringUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Host", "xxx.in");
/* Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("val1", from)
.appendQueryParameter("val2", to);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();*/
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.toString();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.toString();
}
}
/*//only for json object not array
JSONObject parentObject = new JSONObject(text);
name = parentObject.getString("Hello");*/
try {
JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray jsonArray = jsonObj.getJSONArray("PrepaidServiceList");
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
c = jsonArray.getJSONObject(i);
id = c.getString("operator_id");
name = c.getString("operator_name");
list.add(name);
}
} catch (Exception e) {
e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = spinner.getSelectedItemPosition();
id_click = spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Problem:
I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".
But i need the "operator_id" of user selected "operator_name"
I have to pass the exact user selected "operator_id" to another class.
If i directly pass the operator_id, it has only the last id which is not the user selected one.
I am confused and don't know how to implement this.
Any Help would be greatly appreciated.
Thanks.
Try this way it worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
In this case you can modify the AsyncTask to return in the doInBackground() method a List<HashMap<Integer, String>>. So you can store both operator_id and operator_name in the list and display each wanted item in the spinner.
Hope it helps!!!
Create a new ArrayList like
operator_List = new ArrayList<String>();
Add value in ArrayList like
opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")
and get operator_id
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
id_click = spinner.getSelectedItemPosition();
String opt_code = operator_List.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
May be help you
Your can get Whole object of selected Spinner item use below code:
Object item = arg0.getItemAtPosition(position);
i create chain spinner that get data from server and return it by json. my firts spinner is fine. in second spinner the json give response but when try to save the renspone in array the asynctask error caused by nullpointerexception. when i check it in log cat there is no null in my json response. so i try to change name of array with same name as first spinner there is no error but the second spinner show same value as first spinner.
my question why my second spinner when name of array different from first spinner is error ?
where is the nullpointerexception error because when i check it there is no null ? how to fixed it ?
there is my LoginActivity.java
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ArrayList<Category> categoriesListKota;
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
categoriesList = new ArrayList<Category>();
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new GetKota().execute();
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Log.e("Response Kota: ", "> " + catObj.getString("id_kota"));
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
my category.java
private String id;
private String name;
public Category(){}
public Category(String id, String name){
this.id = id;
this.name = name;
}
public void setId(String id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public String getName(){
return this.name;
}
my serviceHandler.java
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
This is Logcat error:
02-05 18:20:48.953: E/Response:(29903): > {"lokasi":[{"id_provinsi":"1","nama":"Bali"},{"id_provinsi":"2","nama":"Banten"},{"id_provinsi":"3","nama":"Bengkulu"},{"id_provinsi":"4","nama":"DI Yogyakarta"},{"id_provinsi":"5","nama":"DKI Jakarta"},{"id_provinsi":"6","nama":"Gorontalo"},{"id_provinsi":"7","nama":"Irian Jaya Barat"},{"id_provinsi":"8","nama":"Jambi"},{"id_provinsi":"9","nama":"Jawa Barat"},{"id_provinsi":"10","nama":"Jawa Tengah"},{"id_provinsi":"11","nama":"Jawa Timur"},{"id_provinsi":"12","nama":"Kalimantan Barat"},{"id_provinsi":"13","nama":"Kalimantan Selatan"},{"id_provinsi":"14","nama":"Kalimantan Tengah"},{"id_provinsi":"15","nama":"Kalimantan Timur"},{"id_provinsi":"16","nama":"Kep. Bangka Belitung"},{"id_provinsi":"17","nama":"Kep. Riau"},{"id_provinsi":"18","nama":"Lampung"},{"id_provinsi":"19","nama":"Maluku"},{"id_provinsi":"20","nama":"Maluku Utara"},{"id_provinsi":"21","nama":"Nanggroe Aceh Darussalaam"},{"id_provinsi":"22","nama":"Nusa Tenggara Barat"},{"id_provinsi":"23","nama":"Nusa Tenggara Timur"},{"id_provinsi":"24","nama":"Papua"},{"id_provinsi":"25","nama":"Riau"},{"id_provinsi":"26","nama":"Sulawesi Selatan"},{"id_provinsi":"27","nama":"Sulawesi Tengah"},{"id_provinsi":"28","nama":"Sulawesi Tenggara"},{"id_provinsi":"29","nama":"Sulawesi Utara"},{"id_provinsi":"30","nama":"Sumatra Barat"},{"id_provinsi":"31","nama":"Sumatra Selatan"},{"id_provinsi":"32","nama":"Sumatra Utara"}]}
02-05 18:20:49.573: E/Response:(29903): > {"lokasi":[{"id_kota":"1","id_provinsi":"1","nama":"KABUPATEN BADUNG"},{"id_kota":"2","id_provinsi":"1","nama":"KABUPATEN BANGLI"},{"id_kota":"3","id_provinsi":"1","nama":"KABUPATEN BULELENG"},{"id_kota":"4","id_provinsi":"1","nama":"KABUPATEN GIANYAR"},{"id_kota":"5","id_provinsi":"1","nama":"KABUPATEN JEMBRANA"},{"id_kota":"6","id_provinsi":"1","nama":"KABUPATEN KARANG ASEM"},{"id_kota":"7","id_provinsi":"1","nama":"KABUPATEN KLUNGKUNG"},{"id_kota":"8","id_provinsi":"1","nama":"KABUPATEN TABANAN"},{"id_kota":"9","id_provinsi":"1","nama":"KOTA DENPASAR"}]}
02-05 18:20:49.573: E/Response Kota:(29903): > 1
02-05 18:20:49.573: W/dalvikvm(29903): threadid=16: thread exiting with uncaught exception (group=0x415b1360)
02-05 18:20:49.603: E/AndroidRuntime(29903): FATAL EXCEPTION: AsyncTask #2
02-05 18:20:49.603: E/AndroidRuntime(29903): java.lang.RuntimeException: An error occured while executing doInBackground()
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$3.done(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.lang.Thread.run(Thread.java:856)
02-05 18:20:49.603: E/AndroidRuntime(29903): Caused by: java.lang.NullPointerException
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:377)
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:1)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$2.call(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-05 18:20:49.603: E/AndroidRuntime(29903): ... 5 more
please help me thanks. sorry i dont know how to post logcat
Try to change these code:
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
to:
private static final String KEY_LOGIN = "login";
private static final String URL_LOGIN = "http://api.omidev.com/login/format/json";
private static final String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
See the difference. The second using static final. Then, change void to String while using String parameter. For example:
private class Login extends AsyncTask<String, Void, Void> {
// Change void to String if the first AsyncTask parameter is a String.
// If the first parameter is Void, change to void (in lowercase)
#Override
protected String doInBackground(String... arg) { // Must be a String type, because the first parameter type is a String.
Sorry my fault. i already fixed my code
in GetKota Asynctask i did not initialized categoriesListKota, so that make it error caused by nullpointerexception.
to make the second spinning change when selected value from first spinning i add notifyDataSetChanged() to change the spinner adapter on populateSpinnerKota() and clear() on GetKota Asynctask to make the spinner clean from previous data.
this is the correct code for LoginActivity.java
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList = new ArrayList<Category>();
private ArrayList<Category> categoriesListKota = new ArrayList<Category>();
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
spinnerAdapter.notifyDataSetChanged();
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
categoriesListKota.clear();
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
I m trying to make json parser for my android application.
I need to post some data after I m getting json object in a while for my listview adapter. I m using this code but its always getting error. I really tried because I change many times but I cant do that. (I can easily get json data, but in this case, I want to make post before JSON parse.) How should I edit my code? Thanks for any help, documents.
I m getting this error :
java.lang.RuntimeException: An error occured while executing doInBackground()
this is my code :
public class veritabaniKayit extends AsyncTask<String, Integer, JSONObject> {
private ProgressDialog pDialog;
JSONObject json2;
#Override
protected void onPreExecute() {
super.onPreExecute();
yayDescription = (TextView)findViewById(R.id.yayDescription);
yayDistance = (TextView)findViewById(R.id.yayDistance);
yayCreatedTime = (TextView)findViewById(R.id.yayCreatedTime);
pDialog = new ProgressDialog(HomeListview.this);
pDialog.setMessage("Wait a min ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0],params[1],params[2]);
JSONParser jParser = new JSONParser();
// Getting JSON from URL
url = "11.22.11.22/messages/list";
System.out.println("THISISMYURL"+url);
json2 = jParser.getJSONFromUrl(url);
return json2;
}
protected void onPostExecute(JSONObject result){
// pb.setVisibility(View.GONE);
}
protected void onProgressUpdate(Integer... progress){
// pb.setProgress(progress[0]);
}
public void postData(String personName, String username, String email) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://11.22.11.22/messages/list");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("token", "zyob3xkdnv"));
nameValuePairs.add(new BasicNameValuePair("lat", "37"));
nameValuePairs.add(new BasicNameValuePair("long", "-122"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// String json2 = EntityUtils.toString(response.getEntity());
/* JSONObject jObject = null;
try {
jObject = new JSONObject(json);
System.out.println("jObject"+jObject);
String tokenValue=jObject.getString("token");
System.out.println("tokenValue"+tokenValue);
edit = pref.edit();
edit.putString("sharedUsername", personName.toString());
edit.putString("sharedEmail", email.toString());
edit.putString("sharedToken", tokenValue);
edit.commit();
}
catch (JSONException e) {
e.printStackTrace();
} */
try {
JSONObject json2;
JSONParser jParser = new JSONParser();
json2 = jParser.getJSONFromUrl(url);
// Getting JSON Array from URL
android = json2.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// String JSON item in a Variable
String yayDescription = c.getString(text);
String yayDistance = c.getString(distance);
String yayCreatedTime = c.getString(created_at);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(text, yayDescription);
map.put(distance, yayDistance);
map.put(created_at, yayCreatedTime);
oslist.add(map);
myOwnPost =(ListView)findViewById(R.id.listView);
myOwnPost.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// myOwnPost.setRotation(-90);
ListAdapter adapter = new SimpleAdapter(HomeListview.this, oslist,
R.layout.homelistviewitem,
new String[] { text, distance, created_at }, new int[] { R.id.yayDescription,R.id.yayDistance, R.id.yayCreatedTime });
myOwnPost.setAdapter(adapter);
myOwnPost.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String whatIsSoundName = oslist.get(+position).get("yayDescription");
Toast.makeText(HomeListview.this, "You Clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
int responseCode = response.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
try to put this code in
#Override
protected void onPostExecute(String result) {
myOwnPost =(ListView)findViewById(R.id.listView);
myOwnPost.setChoiceMode(ListView.CHOICE_MODE_SINGLE);ListAdapter adapter = new SimpleAdapter(HomeListview.this, oslist,
R.layout.homelistviewitem,
new String[] { text, distance, created_at }, new int[] { R.id.yayDescription,R.id.yayDistance, R.id.yayCreatedTime });
myOwnPost.setAdapter(adapter);
myOwnPost.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String whatIsSoundName = oslist.get(+position).get("yayDescription");
Toast.makeText(HomeListview.this, "You Clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
}
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);
}
});