Related
I'm currently studying this tutorial http://www.android-examples.com/android-json-parsing-retrieve-from-url-and-set-mysql-db-data/
It runs perfectly but now I would like to display all of the JSON values in the text view. I am new to JSON and only has a bit of experience in android.
Here is my MainActivity.java. I modified it a bit from the tutorial
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
}
and this is my JSON. It is a lot different from the tutorial
[{"id":"1","name":"white","status":"0"},{"id":"2","name":"red","status":"10"},{"id":"5","name":"blue","status":"15"}]
So obviously my code only displays the first name "white". I can't understand how to iterate the JSONObject to display all the values. I tried the answers in other questions but I can't quite incorporate them in my code.
That's because you're just getting the first element from JSONArray. (Index 0)
You should iterate over JSONArray to get all the JSONObject within an array.
Like this,
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i); // Replace 0 with i'th index.
// use this json object to iterate over individual objects.
}
Here's example of json parsing and insert , update , delete or get data from server with source you should try this !
Happy Coding!
The problem of your code is what Alok Patel stated. But I see that the logic of your code needs some changes to do what you want (according to sample json that you posted). You called parse method on values which are in fact simple data while you should call it on jsonObjects.
I refactored your code as below to do what you want:
public class MainActivity extends Activity {
TextView textview;
JSONObject json = null;
String str = "";
HttpResponse response;
Context context;
ProgressBar progressbar;
Button button;
JSONArray jArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar)findViewById(R.id.progressBar1);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressbar.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
new GetTextViewData(context).execute();
}
});
}
private class GetTextViewData extends AsyncTask<Void, Void, Void>
{
public Context context;
Map<String,String> out = new Map<String, String>();
public GetTextViewData(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.9:80/test-androidex/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
int total=jArray.length();
for(int i=0;i<total;i++) {
JSONObject json = jArray.getJSONObject(i);
parse(json, out);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
// print "out" object to console here by iterating over its keys
// or do any needed process on it here.
textview.setText(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressbar.setVisibility(View.GONE);
}
Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
val = json.getString(key);
}catch(Exception e){
}
if(val != null){
out.put(key,val);
}
}
return out;
}
}
I have an activity class along with customlistadapter inside customlist adapter.
I have a thread runouithread which give me error msg when i wrap it with ((Activity) context).runOnUiThread(new Runnable().
it throws the error msg at runtime has ClassCastException: android.app.Application cannot be cast to android.app.Activity.
So please some one help me.
public class CustomListAdapterfriend extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
URL urll;
HttpURLConnection connection;
InputStream input;
ViewHolder viewHolder;
//UI for Locations
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2,emasr,cn;
ArrayList<String> listItems;
ListView lv;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
int position2;
String id,emm;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email,session_ph,session_type,session_loc,connter;
ArrayList<HashMap<String, Object>> usersList,usersList1;
JSONParser jParser = new JSONParser();
int i ;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
private String imagePath = IP+"/social/upload/";
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_properties5 = IP+"/social/get_all_agen_like.php";
private static String url_all_properties1 = IP+"/social/get_lik_coun.php";
private static String url_all_properties6 = IP+"/social/get_all_agen_like3.php";
private static String url_all_properties7 = IP+"/social/get_all_dele_like.php";
private static String url_all_properties8 = IP+"/social/get_all_dele_uplike.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt,idas5,emasr,cn;
// public String id,emm;
public ImageView like;
public ImageView share;
/*public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}*/
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( final int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
sPref= context.getSharedPreferences("REAL", Context.MODE_PRIVATE);
session_email = sPref.getString("SESSION_UID","");
session_ph = sPref.getString("SESSION_PH","");
session_type = sPref.getString("SESSION_TYPE", "");
session_loc = sPref.getString("SESSION_LOC", "");
// lv=(ListView)view.findViewById(R.id.list);
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.idas5 = (TextView) view.findViewById(R.id.hpid);
viewHolder. emasr= (TextView) view.findViewById(R.id.ema);
viewHolder.like=(ImageView)view.findViewById(R.id.likem);
viewHolder.share=(ImageView)view.findViewById(R.id.sharemsp);
viewHolder.cn = (TextView) view.findViewById(R.id.count);
viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
HashMap<String, Object> item = models.get(position);
String imagePath = (String)item.get("IMAGE").toString();
try {
urll = new URL(imagePath);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = (HttpURLConnection) urll.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setDoInput(true);
try {
connection.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap immutableBpm = BitmapFactory.decodeStream(input);
if(immutableBpm !=null)
{
Bitmap mutableBitmap = immutableBpm.copy(Bitmap.Config.ARGB_8888, true);
View view = new View(context);
view.draw(new Canvas(mutableBitmap));
String path = Images.Media.insertImage(context.getContentResolver(), mutableBitmap, "Nur", null);
Uri uri = Uri.parse(path);
/* image = (ImageView) view.findViewById(R.id.feedImage1);
Drawable mDrawable = image.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
String path = Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);*/
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
else
{
Toast.makeText(context, "No image to share", Toast.LENGTH_LONG).show();
}
}
});
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
viewHolder.idas5.setText((CharSequence) item.get("UIDAS"));
// id=(String) viewHolder.idas5.getText();
viewHolder.emasr.setText((CharSequence) item.get("EMAILM"));
id=(String) viewHolder.idas5.getText();
emm=(String) viewHolder.emasr.getText();
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
/*if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//viewHolder.like.setBackgroundResource(R.drawable.like2);
new LoadAllProducts7().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}
else if(!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
// viewHolder.like.setBackgroundResource(R.drawable.like1);
new LoadAllProducts().execute();
new LoadAllProducts22().execute();
notifyDataSetChanged();
}*/
}
});
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.like.setTag(position);
viewHolder.share.setTag(position);
final HashMap<String, Object> item = getItem(position);
/* name.setText(((String)item.get(R.id.name)));
*
*
*/
new LoadAllProducts78().execute();
// boolean isSelected = (Boolean) item.get("selected");
/*if (viewHolder.like.isSelected()) {
viewHolder.like.setSelected(false);
viewHolder.like.setBackgroundResource(R.drawable.like2);
} else if (!viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.like1);
} */
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
idas.setText((CharSequence) item.get("UIDAS"));
viewHolder.cn.setText((CharSequence) item.get("COUN"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().
getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,image.getHeight())
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
return view;
}
protected ContentResolver getContentResolver() {
// TODO Auto-generated method stub
return null;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties5, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
Log.d("Inside success...", json.toString());
connter = json.getString("loca");
Intent intent = ((Activity) context).getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
sPref.edit().putString("SESSION_UID", session_email).commit();
sPref.edit().putString("SESSION_TYPE", session_type).commit();
sPref.edit().putString("SESSION_PH", session_ph).commit();
sPref.edit().putString("SESSION_LOC", session_loc).commit();
((Activity) context).finish();
((Activity) context).overridePendingTransition(0, 0);
((Activity) context).startActivity(intent);
((Activity) context).overridePendingTransition(0, 0);
//Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
else if (success== 5){
// no products found
Toast.makeText(context, "Already liked", Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
// pDialog.dismiss();
}
}
class LoadAllProducts78 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*pDialog = new ProgressDialog(Friendsprofile.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
*/
/*Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
//usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties6, "POST", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All bastart: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
viewHolder.like.setBackgroundResource(R.drawable.like1);
viewHolder.like.setSelected(true);
}
else if(success == 2) {
viewHolder.like.setBackgroundResource(R.drawable.like2);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
//pDialog.dismiss();
}
}
class LoadAllProducts22 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_properties1, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All Productgetting start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
class LoadAllProducts7 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);*/
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
// session_email = sPref.getString("SESSION_UID","");
usersList = new ArrayList<HashMap<String, Object>>();
//usersList1 = new ArrayList<HashMap<String, Object>>();
// id=(String) viewHolder.idas5.getText();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", session_email));
params.add(new BasicNameValuePair("loc", "liked"));
params.add(new BasicNameValuePair("con", "1"));
params.add(new BasicNameValuePair("idtes", id));
params.add(new BasicNameValuePair("emas", emm));
JSONObject json = jParser.makeHttpRequest(url_all_properties7, "GET", params);
if (json != null) {
// Check your log cat for JSON reponse
Log.d("All start: ", json.toString());
// Checking for SUCCESS TAG
try {
int success = json.getInt(TAG_SUCCESS);
if (success== 1) {
// new LoadAllProducts22().execute();
// products found
// Getting Array of Products
/*users = json.getJSONArray(TAG_PRO);
//users1 = json.getJSONArray(TAG_PRO1);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
//ImageView imageView = (ImageView) findViewById(R.id.profilePic);
// Storing each json item in variable
//String scpass = countt.getText().toString();
String uid = c.getString("uid1"); //from php blue
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put("UIDAS", uid); //from
map.put("PIC", pic);
usersList.add(map);
//usersList1.add(map);
// creating new HashMap
}*/
}
else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
Because while calling this constructor:
CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
You are providing getApplicationContext(). Try to provide context of the activity.
Edit 1:
Following the comments:
CustomListAdapterfriend adapter = new CustomListAdapterfriend(Friendsprofile.this, usersList); lv.setAdapter(adapter);
Modify the constructor of your adapter class from
public CustomListAdapterfriend(Context context, List<HashMap<String, Object>> models)
to
public CustomListAdapterfriend(Activity context, List<HashMap<String, Object>> models)
So whenever you call the constructor, the IDE will notify you to provide an Activity as a parameter, so the cast in your adapter won't fail.
While using in fragments try requireActivity() instead of getApplicationContext()
CustomListAdapterfriend(requireActivity(), List<HashMap<String, Object>> models)
When the splash activity launches, the next acivity users login in. usernames and passwords are stored in mysql db. the link is properly establish but Enob_login activity
tells me to check my internet connection yet when i run the ipaddress
on my pc browser (http://192.168.1.11/EnoticeWeb/DB_Enob_Frame.php) i can view the json printout:
[{"0":"1","cnb_id":"1","1":"Admin","cnb_name":"Admin","2":"admin","cnb_pwd":"admin"},
{"0":"2","cnb_id":"2","1":"Hod","cnb_name":"Hod","2":"hod","cnb_pwd":"hod"},
{"0":"3","cnb_id":"3","1":"Staff","cnb_name":"Staff","2":"staff","cnb_pwd":"staff"},
{"0":"4","cnb_id":"4","1":"Student","cnb_name":"Student","2":"student","cnb_pwd":"student"}];
Please help me out!!!!!!!!!!
this is my NetConnection.java codes
public class NetConnection extends Activity {
private SharedPreferences prefs;
private String prefName = "report";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String net_ip=prefs.getString("ip", "http://192.168.1.11/enoticeweb/");
URL url = new URL(net_ip);
executeReq(url);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("connection", 1);
editor.commit();
finish();
startActivity(new Intent(NetConnection.this,Enob_Login.class));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Check Network Connection " +
"and IP Address ", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("connection", 0);
editor.commit();
finish();
startActivity(new Intent(NetConnection.this,Enob_Login.class));
}
}
public void executeReq(URL urlObject) throws IOException {
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlObject.openConnection();
conn.setReadTimeout(30000);//milliseconds
conn.setConnectTimeout(3500);//milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start connect
conn.connect();
InputStream response =conn.getInputStream();
Log.d("Response:", response.toString());
}
}
and my Enob_login.java codes
public class Enob_Login extends Activity {
Spinner Spinn_Frame;
EditText Edit_Frame_Pwd;
Button But_Go;
List<String> List_Frame, List_Frame_Pwd, List_cnbid;
String Str_Frame_Pwd, Str_Alert_Msg, Str_Alert_Title;
int Int_Frame_Pos;
InputStream is=null;
String result=null;
String line=null;
String IP_Address;
private SharedPreferences prefs;
private String prefName = "report";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enob_login);
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
int Conn_Check = prefs.getInt("connection", 100);
if(Conn_Check == 0)
{
AlertDialog.Builder Alert_Conn_Error = new AlertDialog.Builder(Enob_Login.this);
Alert_Conn_Error.setMessage("Check your Internet Connection..");
Alert_Conn_Error.setTitle("Connection Error");
Alert_Conn_Error.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
Alert_Conn_Error.show();
}
else {
initialise_variables();
ArrayAdapter<String> adp = new ArrayAdapter<String>
(this, android.R.layout.simple_expandable_list_item_1, List_Frame);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinn_Frame.setAdapter(adp);
Int_Frame_Pos = 0;
Spinn_Frame.setSelection(Int_Frame_Pos);
Str_Frame_Pwd = List_Frame_Pwd.get(Int_Frame_Pos).toString();
Spinn_Frame.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Int_Frame_Pos = arg2;
Str_Frame_Pwd = List_Frame_Pwd.get(Int_Frame_Pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
But_Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(Edit_Frame_Pwd.getText().toString().equalsIgnoreCase("")) {
Str_Alert_Msg = "Enter Password !!!";
Str_Alert_Title = "Error";
alert_method();
}
else {
if(Edit_Frame_Pwd.getText().toString().equals(Str_Frame_Pwd)) {
if(Int_Frame_Pos == 0) {
save();
}
if(Int_Frame_Pos == 1) {
save();
}
if(Int_Frame_Pos == 2) {
save();
}
if(Int_Frame_Pos == 3) {
save();
}
}
else {
Str_Alert_Msg = "Wrong Password !!!";
Str_Alert_Title = "Error";
alert_method();
}
}
}
private void save() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putInt("cnb_id",
Integer.parseInt(List_cnbid.get(Int_Frame_Pos).toString()));
//---saves the values---
editor.commit();
finish();
Intent i = new Intent(Enob_Login.this, User_Login.class);
startActivity(i);
Edit_Frame_Pwd.setText(null);
}
});
}
}
public void initialise_variables() {
Spinn_Frame = (Spinner) findViewById(R.id.spinner1);
Edit_Frame_Pwd = (EditText) findViewById(R.id.editText1);
But_Go = (Button) findViewById(R.id.button1);
List_Frame = new ArrayList<String>();
List_Frame_Pwd = new ArrayList<String>();
List_cnbid = new ArrayList<String>();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
IP_Address = prefs.getString("ip", "http://192.168.1.11/enoticeweb/");
DB_Enob_Frame();
}
public void DB_Enob_Frame() {
// TODO Auto-generated method stub
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(IP_Address + "DB_Enob_Frame.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
try
{
JSONArray jarray = new JSONArray(result);
JSONObject jobj = null;
for(int i=0; i<jarray.length(); i++) {
jobj = jarray.getJSONObject(i);
List_Frame.add(jobj.getString("cnb_name"));
List_Frame_Pwd.add(jobj.getString("cnb_pwd"));
List_cnbid.add(String.valueOf(jobj.getInt("cnb_id")));
}
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("ip", IP_Address);
editor.commit();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
}
public void alert_method() {
AlertDialog.Builder alert = new AlertDialog.Builder(Enob_Login.this);
alert.setMessage(Str_Alert_Msg);
alert.setTitle(Str_Alert_Title);
alert.setPositiveButton("OK", null);
alert.show();
Edit_Frame_Pwd.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
}
}
My custom adapter for notification
public class SchoolTagAdapter extends BaseAdapter {
Context context;
SharedPreferences prefs;
LayoutInflater inflater;
Boolean toggle_status;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public SchoolTagAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
OnItemClickListener(int position)
{
mPosition = position;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
SchoolDetails schoolDetail = (SchoolDetails)context;
schoolDetail.onItemClick(mPosition);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView id;
TextView name;
final ToggleButton toogle;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.schooltag_list, parent, false);
// Get the position
resultp = data.get(position);
id = (TextView)itemView.findViewById(R.id.textView1);
name = (TextView)itemView.findViewById(R.id.tagname);
toogle = (ToggleButton)itemView.findViewById(R.id.toggleButton1);
name.setText(resultp.get(SchoolDetails.NAME));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
toggle_status = preferences.getBoolean("NameOfThingToSave",true);
Log.d("TOGGLE_STATUS", toggle_status+"");
if(toggle_status==true)
{
toogle.setChecked(true);
}
else if(toggle_status==false)
{
toogle.setChecked(false);
}
toogle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//TODO Auto-generated method stub
if (toogle.isChecked())
{
prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("NameOfThingToSave",true);
prefEditor.commit();
}
else if(!toogle.isChecked())
{
prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("NameOfThingToSave",false);
prefEditor.commit();
}
}
});
itemView.setOnClickListener(new OnItemClickListener(position));
return itemView;
}
}
This is my Activity
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.schoolzine.adapters.SchoolTagAdapter;
import com.example.schoolzine.asyncimages.ImageLoader;
import com.example.schoolzine.database.DatabaseHandler;
import com.example.schoolzine.models.SchoolTag;
import com.example.schoolzine.utils.JsonParsor;
import com.example.schoolzine.utils.WebserviceUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class SchoolDetails extends Activity {
public static String id;
public int t,parn,stud,stff;
TextView Name,City,State,Street,Tag;
Button back, next;
String schoolName,schoolStreet,schoolCity,schoolState,schoolImage,schoolId,schoolUrl,schoolid,
schoolPOBox,schoolPhone,schoolWebsite,schoolPrefix,schoolURL,schoolnotId,schoolnotifName;
int schoolnotifId;
public String TAG1,TAG2,TAG3,spinnerValue;
ImageView Image;
ImageLoader SchoolImageLoader = new ImageLoader(SchoolDetails.this);
JSONObject jobject, jobj;
public ProgressDialog p_dialog;
ArrayList<HashMap<String, String>> arraylist;
Spinner spin;
HashMap queryValues;
DatabaseHandler dbHandler;
SharedPreferences pref;
boolean toggle_status;
SharedPreferences preferences;
public static String ID = "id";
public static String NAME = "name";
public static String DESCRIPTION = "description";
ListView listview;
SchoolTagAdapter sadapter;
ArrayList<SchoolTag> schoolTAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schooldetails);
dbHandler = new DatabaseHandler(SchoolDetails.this);
if(android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getActionBar().hide();
Image = (ImageView)findViewById(R.id.schoolimage);
Name = (TextView)findViewById(R.id.name);
Street = (TextView)findViewById(R.id.street);
City = (TextView)findViewById(R.id.city);
State = (TextView)findViewById(R.id.state);
Tag = (TextView)findViewById(R.id.tagname);
listview = (ListView)findViewById(R.id.listView1);
spin = (Spinner)findViewById(R.id.spinner1);
back = (Button)findViewById(R.id.back);
next = (Button)findViewById(R.id.next);
schoolTAG = new ArrayList<SchoolTag>();
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
toggle_status = preferences.getBoolean("NameOfThingToSave", false);
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolDetailTask().execute(WebserviceUtil.WEBSERVICE_URL+"school/"+id+".json");
}
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2 == 0) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag1Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG);
// listview.setAdapter(sadapter);
}
if(arg2 == 1) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag2Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG); ;
// listview.setAdapter(sadapter);
}
if(arg2 == 2) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag3Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG); ;
// listview.setAdapter(sadapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent(SchoolDetails.this, StateSchoolList.class);
startActivity(inten);
finish();
}
});
if(dbHandler.doesIdExist(id)) {
next.setVisibility(View.INVISIBLE);
}
else {
next.setOnClickListener(new OnClickListener() {
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
queryValues = new HashMap();
queryValues.put("sId", schoolid);
queryValues.put("sName", schoolName);
queryValues.put("sStreet", schoolStreet);
queryValues.put("sState", schoolState);
queryValues.put("sCity", schoolCity);
queryValues.put("sPOBox", schoolPOBox);
queryValues.put("sPhone", schoolPhone);
queryValues.put("sWebsite", schoolWebsite);
queryValues.put("sImage", schoolImage);
queryValues.put("sURL", schoolURL);
queryValues.put("sPrefix", schoolPrefix);
dbHandler.insertSchoolDetails(queryValues);
Intent intent = new Intent(SchoolDetails.this, Registration.class);
startActivity(intent);
}
});
}
}
private class SchoolDetailTask extends AsyncTask<String, String, String>
{
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#SuppressWarnings({ "rawtypes" })
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.WEBSERVICE_URL+"school/"+id+".json");
queryValues = new HashMap();
try {
JSONObject jobj = jobject.getJSONObject("school");
schoolid = jobj.getString("id");
schoolName = jobj.getString("name");
schoolStreet = jobj.getString("physical_street");
schoolCity = jobj.getString("physical_city");
schoolState = jobj.getString("physical_state");
schoolPOBox = jobj.getString("physical_postcode");
schoolPhone = jobj.getString("phone");
schoolWebsite = jobj.getString("website");
schoolPrefix = jobj.getString("prefix");
schoolImage = jobj.getString("logo");
schoolURL = jobj.getString("url");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "sucess";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if(p_dialog != null) {
p_dialog.dismiss();
}
// sadapter.notifyDataSetChanged();
super.onPostExecute(result);
if(result.compareTo("sucess") == 0) {
Name.setText(schoolName);
Street.setText(schoolStreet);
City.setText(schoolCity);
State.setText(schoolState);
SchoolImageLoader.DisplayImage(schoolImage, Image);
}
}
}
private class SchoolNotifTag1Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG1);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG1_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
private class SchoolNotifTag2Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG2);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG2_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
private class SchoolNotifTag3Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG3);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG3_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
public static void values(String ID) {
// TODO Auto-generated method stub
id = ID;
}
public void onItemClick(int mPosition) {
// TODO Auto-generated method stub
toggle_status = preferences.getBoolean("NameOfThingToSave", true);
if (toggle_status == true) {
// Toast.makeText(SchoolDetails.this, "Toogle "+toggle_status+" at position "+mPosition,
// Toast.LENGTH_SHORT).show();
// player.start();
// Log.d("MUSIC pLAYER", "STARTED");
}
else if (toggle_status == false) {
// Toast.makeText(SchoolDetails.this, "Toogle "+toggle_status+" at position "+mPosition,
// Toast.LENGTH_SHORT).show();
// player.stop();
// Log.d("MUSIC pLAYER", "STOPPED");
}
}
}
I tried to parse JSON values into a custom ListView.
My custom ListView contains a TextView and a toggle button. It's a notification activity. I turn notifications on and off by using a toggle button in a custom ListView.
The JSON values parsed fine. I limited my ListView height to 150dp.
My problem is that, suppose if my ListView contains 20 values parsed. When I put on first list item and when I scrolled down, the last few items also automatically turned on. I think it may because of recreating ListView, but I don’t know how to solve it.
What I want is to save state of each toggle button in ListView I turned on/off.
Anybody have any idea?
if (convertView == null) {
//inflating views
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
I'm using Android SDK 4.0 API14 and I want to run multiple AsyncTask in one class, I want the called async task to wait while the one before it is finished, but is seems I can't accomplish this, even if I test the status of the one currently being executed. this is my code :
if(isNetworkAvailable()){
new SpinnerTask().execute();
new RiderTask().execute();
new BankTask().execute();
}
//spinner bank
public class BankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=pusat";
public BankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Bank");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK PUSAT");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBP_NAMA = spinner.optString("LSBP_NAMA");
int LSBP_ID = spinner.optInt("LSBP_ID");
helper.InsertBank(LSBP_ID, LSBP_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner bank
public class CabBankTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_bank.htm?type=cabang";
public CabBankTask(){
this.url=url;
System.out.println(url);}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
// Response(result.replace("\n", "").trim());
System.out.println("done for Cabang");
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("BANK CABANG");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
int LSBP_ID = spinner.optInt("LSBP_ID");
int LBN_ID = spinner.optInt("LBN_ID");
String LBN_NAMA = spinner.optString("LBN_NAMA");
helper.InsertCabBank(LSBP_ID, LBN_ID, LBN_NAMA);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
}
}catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//spinner produk
public class SpinnerTask extends AsyncTask<Void, Void, String>{
// String url="http://epolicy.sinarmasmsiglife.co.id/ios/spaj_prod.htm?model=1";
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=bancass";
public SpinnerTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
// dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Produk..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// dialog.dismiss();
super.onPostExecute(result);
fetchResponse(result.replace("\n", "").trim());
System.out.println("done for product");
}
}
private void fetchResponse(String result) {
if (!result.equals("")) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray PRODUK = jsonObject.getJSONArray("PRODUK");
for (int i=0; i<PRODUK.length();i++){
JSONObject spinner = PRODUK.getJSONObject(i);
String LSBS_ID = spinner.optString("LSBS_ID");
String LSBS_NAME = spinner.optString("LSBS_NAME");
helper.InsertSpin_Produk(LSBS_ID, LSBS_NAME);
// ListSpinner.add(VarSpinner);
System.out.println("tes VarSpinner");
JSONArray PRODUK1 = spinner.getJSONArray("SUB_PRODUK");
for (int j=0; j<PRODUK1.length();j++){
JSONObject sub = PRODUK1.getJSONObject(j);
String LSDBS_NUMBER = sub.optString("LSDBS_NUMBER");
String LSDBS_NAME = sub.optString("LSDBS_NAME");
helper.InsertSpin_SubProduk(LSBS_ID,LSBS_NAME,LSDBS_NUMBER, LSDBS_NAME);
System.out.println("tes VarSpinner 1\2");
}
}
}
catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
//Rider
public class RiderTask extends AsyncTask<Void, Void, String>{
String url="http://128.21.30.37:8080/E-Policy/ios/spaj_prod.htm?type=rider";
public RiderTask(){
this.url=url;
System.out.println(url);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(Menu_SPPAJ.this);
dialog = ProgressDialog.show(Menu_SPPAJ.this, "Mohon Menunggu", "Penarikan data Rider..");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
System.out.println("tes " + result);
} catch (Exception e) {
// TODO: handle exception
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// TODO Auto-generated method stub
super.onPostExecute(result);
Response(result.replace("\n", "").trim());
System.out.println("done for ridern");
}
}
is there any way to run multiple Asynctask in one class? thank u very much
Have a look on the AsyncTask.executeOnExecutor() method. It will run AsyncTasks in parallel. But make sure that the Tasks you run are independent from each other. As mentioned in the docs there is no given order in which the Tasks will be executed.
Call your Tasks like this:
new SpinnerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
What you can do is, you can call second AsyncTask on onPostExecute() of first AsyncTask and so on.
e.g
public class FirstAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// your code
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// new SecondAsyncTask().execute();
}}