I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}
Related
iam creating an App which should show the Sights in a Listview.
The datas are parsed from a json.
At this json there is a column which declares in which City the sight is.
Now i would like to create a kind of a filter which should check the current Cityname with the City values in my Json.
For example there is a Sight in Berlin and my current city is Berlin, the Listview should show it. If the user is in Munich and the sight is in Berlin, the listview shouldnt show this item.
I get the current cityname value from a different Activity in a TextView.
Here is my Listview Activity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity;
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
Get current city name from intent.
String currentCityName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
currentCityName = i.getExtras().getString("cityname");
...........
.................
}
Add condition to match cityName with currentCityName before adding productforloc object to ArrayList:
try {
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
String cityName = po.getString("city");
if(!cityName.equals(currentCityName)) {
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm pretty new to android dev and I need some help.
I'm building an agenda that loads the information from a JSON then a ListView is inflated with a custom adapter. I've done this and works just fine.
My problem is the following when I click a contact another Activity is loaded with more information about the user, using the same JSON. I debug it and it recieves the information like this:
Example Item: [{"id":1,"name":"Leanne Graham","hobby":"Play soccer","address":"Kulas Light, Gwenborough","phone":"1-770-736-8031 x56442"}]
Because I sent the information as a JSONObject I cast it to be a JSONArray, but when I pass that array to my requestComplete my app breaks.
The error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
/**Main activity onclick listener*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("POSITION: " + position);
JSONObject jsonObject = (JSONObject)JSONadapter.getItem(position);
Intent intent = new Intent(this, InfoActivity.class);
String pos_json = jsonObject.toString();
intent.putExtra("pos_json",pos_json);
startActivity(intent);
}
/**Info activity*/
public class InfoActivity extends AppCompatActivity implements JSONRequest.JSONCallback {
AdapterInfo JSONAdapter;
private ListView listInfo;
private JSONObject json_object;
private JSONArray arrayMain;
private ArrayList<String> jsonarray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
JSONArray array = new JSONArray();
try {
json_object = new JSONObject(getIntent().getStringExtra("pos_json"));
arrayMain = array.put(json_object);
System.out.println("Example Item: "+ arrayMain.toString());
System.out.println(arrayMain.getClass().getName());
} catch (JSONException e) {
e.printStackTrace();
}
requestComplete(arrayMain);
this.listInfo = (ListView) findViewById(R.id.listView2);
}
#Override
public void requestComplete(JSONArray array) {
JSONAdapter = new AdapterInfo(InfoActivity.this,array);
this.listInfo.setAdapter(JSONAdapter);
}
/**Adapter*/
public class AdapterInfo extends BaseAdapter{
private JSONArray array;
private Activity infoAct;
public AdapterInfo(Activity infoAct, JSONArray array){
this.array = array;
this.infoAct = infoAct;
}
#Override
public int getCount() {
if(array == null){
return 0;
}else{
return array.length();
}
}
#Override
public JSONObject getItem(int position) {
if(array == null){
return null;
}else{
return array.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = infoAct.getLayoutInflater().inflate(R.layout.row,null);
}
TextView name = (TextView)convertView.findViewById(R.id.infoName);
TextView hobby = (TextView)convertView.findViewById(R.id.infoHobby);
TextView address = (TextView)convertView.findViewById(R.id.infoAddress);
TextView phone = (TextView)convertView.findViewById(R.id.infoPhone);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String nombre = json_data.getString("name");
String pasatiempo = json_data.getString("hobby");
String direccion = json_data.getString("address");
String telefono = json_data.getString("phone");
name.setText(nombre);
hobby.setText(pasatiempo);
address.setText(direccion);
phone.setText(telefono);
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}}
/**JSONRequest*/
public class JSONRequest extends AsyncTask<String, Void, JSONArray> {
private JSONCallback callback;
public JSONRequest(JSONCallback callback){
this.callback = callback;
}
#Override
protected JSONArray doInBackground(String... params) {
URLConnection connection = null;
BufferedReader br = null;
JSONArray result = null;
try{
URL url = new URL(params[0]);
connection = (URLConnection) url.openConnection();
InputStream is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = "";
while((line = br.readLine()) != null){
builder.append(line);
}
result = new JSONArray(builder.toString());
}catch (Exception e) {
e.printStackTrace();
} finally {
try{
if(br != null) br.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
callback.requestComplete(jsonArray);
}
public interface JSONCallback{
void requestComplete(JSONArray array);
}}
Your code:
requestComplete(arrayMain);
this.listInfo = (ListView) findViewById(R.id.listView2);
requestComplete() uses this.listInfo instance but this.listInfo is null because it is set after requestComplete(). So you need to switch their order.
this.listInfo = (ListView) findViewById(R.id.listView2);
requestComplete(arrayMain);
It is better if you just put it right after call to setContentView() just to make sure this.listInfo holds valid ListView instance.
I am new in android and am working with a project that loads data from internet into listview. I got my prototype here: kaleidosblog.com/android-listview-load-data-from-json
So these will be the json links:
http://www.funtrial.com/christiancepe/announcements/json.php?page=1
http://www.funtrial.com/christiancepe/announcements/json.php?page=2
So on..
In my activity, I have my EditText, Button and ListView.
Editext will get the url.
Button will be use to load the json link (from url) to listview
Listview will display datas
In my current program, it only works on first click of button. So once I entered the first json, it will show the correct data. But when I try to change the json on EditText, still the ListView is populated by the first json. In short, my ListView does not refresh everytime I am changing the link and clicking the button.
What's wrong with this?
Main Activity:
protected void onCreate(Bundle savedInstanceState) {
final Button searchButton = (Button) findViewById(R.id.searchButton);
final EditText searchForm = (EditText) findViewById(R.id.searchForm);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(MainActivity.this);
list.setAdapter(adapter);
search = searchForm.getText().toString();
Download_data download_data = new Download_data((download_complete) MainActivity.this);
download_data.download_data_from_link(search);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), search, Toast.LENGTH_LONG).show();
}
});
}
public void get_data(String data){
try {
JSONObject jsonObj = new JSONObject(data);
JSONArray data_array = jsonObj.getJSONArray("announcements");
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.name = obj.getString("message");
add.code = obj.getString("date");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Download_data.java
public class Download_data implements Runnable {
public download_complete caller;
public interface download_complete{
public void get_data(String data);
}
Download_data(download_complete caller) {
this.caller = caller;
}
private String link;
public void download_data_from_link(String link){
this.link = link;
Thread t = new Thread(this);
t.start();
}
public void run() {
threadMsg(download(this.link));
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String Response = msg.getData().getString("message");
caller.get_data(Response);
}
};
public static String download(String url) {
URL website;
StringBuilder response = null;
try {
website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (Exception e) {
return "";
}
return response.toString();
}
ListAdapter.java
MainActivity main;
ListAdapter(MainActivity main)
{
this.main = main;
}
#Override
public int getCount() {
return main.countries.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolderItem {
TextView name;
TextView code;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.code = (TextView) convertView.findViewById(R.id.code);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderItem) convertView.getTag();
}
holder.name.setText(this.main.countries.get(position).name);
holder.code.setText(this.main.countries.get(position).code);
return convertView;
}
It appears that the countries list is being added to each time in get_data(), but never cleared out. At the start of get_data, you most likely want to clear the countries list with the following call:
countries.clear();
Then the data in the countries list will be cleared out, the new downloaded data will be added to the countries list, and then updated in the view when the adapter is notified of the data change.
I am working on a project that has a custom listview containing dynamic data. What I want is to fetch that data in an arraylist then pass it to the php file for further processing. I am able to do this for single values but for multiple values I don't have any idea.
This is my adapter class:
public class ListAdapter extends ArrayAdapter {
//static String get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static List list=new ArrayList();
static String[] get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static String sting_length;
int i;
public ListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Details object) {
super.add(object);
list.add(object);
}
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
final DetailsHolder detailsHolder;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.list_layout_approval, parent, false);
detailsHolder=new DetailsHolder();
detailsHolder.empcode=(TextView) row.findViewById(R.id.empcode1);
detailsHolder.empname=(TextView) row.findViewById(R.id.empname1);
detailsHolder.appdate=(TextView) row.findViewById(R.id.appdate1);
detailsHolder.lv_type=(TextView) row.findViewById(R.id.lv_type1);
detailsHolder.from=(TextView) row.findViewById(R.id.from1);
detailsHolder.to=(TextView) row.findViewById(R.id.to1);
detailsHolder.nod=(TextView) row.findViewById(R.id.nod1);
detailsHolder.reason=(TextView) row.findViewById(R.id.reason1);
detailsHolder.status=(TextView) row.findViewById(R.id.status1);
detailsHolder.cb2=(CheckBox) row.findViewById(R.id.cb2);
// Leave_approval la=new Leave_approval();
/*
if( Leave_approval.cb_status==true){
detailsHolder.cb2.setChecked(true);
}
else
{
detailsHolder.cb2.setChecked(false);
}
*/
DetailsHolder.cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(DetailsHolder.cb2.isChecked())
{
get_empcode=(String) detailsHolder.empcode.getText();
get_from=(String) detailsHolder.from.getText();
get_to=(String) detailsHolder.to.getText();
get_lv_type=(String) detailsHolder.lv_type.getText();
get_nod=(String) detailsHolder.nod.getText();
get_status=(String) detailsHolder.status.getText();
}
}
});
row.setTag(detailsHolder);
}
else{
detailsHolder=(DetailsHolder) row.getTag();
}
Details details=(Details)this.getItem(position);
detailsHolder.empcode.setText(details.getEmpcode());
detailsHolder.empname.setText(details.getEmpname());
detailsHolder.appdate.setText(details.getApplyDate());
detailsHolder.lv_type.setText(details.getLeave_type());
detailsHolder.from.setText(details.getFrom());
detailsHolder.to.setText(details.getTo());
detailsHolder.nod.setText(details.getNod());
detailsHolder.reason.setText(details.getReason());
detailsHolder.status.setText(details.getStatus());
return row;
}
here is my Activity file from where I am passing data to php using async task
public class Leave_approval extends Activity {
String JSON_STRING,php_result,LeaveType,empcode,FullName,ApplyDate,From,To,NOD,Reason,Status;
//String empcode_val="",lv_type_val="",nod_value="",status_val="",from_value="",to_value="";
String[] empcode_val,lv_type_val,nod_value,status_val,from_value,to_value;
JSONObject jsonObject;
JSONArray jsonArray;
String[] date_list;
ArrayList<HashMap<String, String>> personList;
TextView head;
ListAdapter listAdapter;
ListView listView;
CheckBox cb1;
static Boolean cb_status;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.leave_approval);
listView=(ListView) findViewById(R.id.list);
cb1=(CheckBox) findViewById(R.id.cb1);
listAdapter=new ListAdapter(this, R.layout.list_layout_approval);
listView.setAdapter(listAdapter);
head=(TextView) findViewById(R.id.head);
Bundle b = getIntent().getExtras();
php_result=b.getString("json_data");
//Toast.makeText(getBaseContext(), php_result, Toast.LENGTH_SHORT).show();
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
jsonObject=new JSONObject(php_result);
jsonArray=jsonObject.getJSONArray("server_response");
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
LeaveType=c.getString("LeaveType");
empcode=c.getString("empcode");
FullName=c.getString("FullName");
ApplyDate=c.getString("ApplyDate");
From=c.getString("From");
To=c.getString("To");
NOD=c.getString("NOD");
Reason=c.getString("Reason");
Status=c.getString("Status");
String[] from_array=From.split("-");
String[] to_array=To.split("-");
String[] apply_array=ApplyDate.split("-");
String from_date,to_date,appdate;
if(from_array[1].equals("01"))
from_array[1]="jan";
if(from_array[1].equals("02"))
from_array[1]="Feb";
if(from_array[1].equals("03"))
from_array[1]="Mar";
if(from_array[1].equals("04"))
from_array[1]="Apr";
if(from_array[1].equals("05"))
from_array[1]="May";
if(from_array[1].equals("06"))
from_array[1]="Jun";
if(from_array[1].equals("07"))
from_array[1]="Jul";
if(from_array[1].equals("08"))
from_array[1]="Aug";
if(from_array[1].equals("09"))
from_array[1]="Sep";
if(from_array[1].equals("10"))
from_array[1]="Oct";
if(from_array[1].equals("11"))
from_array[1]="Nov";
if(from_array[1].equals("12"))
from_array[1]="Dec";
if(to_array[1].equals("01"))
to_array[1]="jan";
if(to_array[1].equals("02"))
from_array[1]="Feb";
if(to_array[1].equals("03"))
to_array[1]="Mar";
if(to_array[1].equals("04"))
to_array[1]="Apr";
if(to_array[1].equals("05"))
to_array[1]="May";
if(to_array[1].equals("06"))
to_array[1]="Jun";
if(to_array[1].equals("07"))
to_array[1]="Jul";
if(to_array[1].equals("08"))
to_array[1]="Aug";
if(to_array[1].equals("09"))
to_array[1]="Sep";
if(to_array[1].equals("10"))
to_array[1]="Oct";
if(to_array[1].equals("11"))
to_array[1]="Nov";
if(to_array[1].equals("12"))
to_array[1]="Dec";
if(apply_array[1].equals("01"))
apply_array[1]="jan";
if(apply_array[1].equals("02"))
apply_array[1]="Feb";
if(apply_array[1].equals("03"))
apply_array[1]="Mar";
if(apply_array[1].equals("04"))
apply_array[1]="Apr";
if(apply_array[1].equals("05"))
apply_array[1]="May";
if(apply_array[1].equals("06"))
apply_array[1]="Jun";
if(apply_array[1].equals("07"))
apply_array[1]="Jul";
if(apply_array[1].equals("08"))
apply_array[1]="Aug";
if(apply_array[1].equals("09"))
apply_array[1]="Sep";
if(apply_array[1].equals("10"))
apply_array[1]="Oct";
if(apply_array[1].equals("11"))
apply_array[1]="Nov";
if(apply_array[1].equals("12"))
apply_array[1]="Dec";
from_date=from_array[2]+"-"+from_array[1]+"-"+from_array[0];
to_date=to_array[2]+"-"+to_array[1]+"-"+to_array[0];
appdate=apply_array[2]+"-"+apply_array[1]+"-"+apply_array[0];
Details details=new Details(empcode,FullName,appdate,LeaveType,from_date,to_date,NOD,Reason,Status);
listAdapter.add(details);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void approve(View view){
String empcode_val="",lv_type_val="",nod_value="",status_val="",from_value="",to_value="";
empcode_val=ListAdapter.get_empcode;
lv_type_val=ListAdapter.get_lv_type;
nod_value=ListAdapter.get_nod;
status_val="Approved";
from_value=ListAdapter.get_from;
to_value=ListAdapter.get_to;
if(empcode_val.equals("")&&lv_type_val.equals("")&&nod_value.equals("")&&status_val.equals("")&&from_value.equals("")
&&to_value.equals("")){
Toast.makeText(getBaseContext(), "Please make some selections",Toast.LENGTH_SHORT).show();
}
else{
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(empcode_val,lv_type_val,nod_value,status_val,from_value,to_value);
}
}
public class BackgroundTask extends AsyncTask {
AsyncResponse delegate = null;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/neha/leave_approval_update.php";
String empcode = params[0];
String leave_type=params[1];
String nod=params[2];
String status=params[3];
String from=params[4];
String to=params[5];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data = URLEncoder.encode("empcode","UTF-8")+"="+URLEncoder.encode(empcode,"UTF-8")+"&"+
URLEncoder.encode("leave_type","UTF-8")+"="+URLEncoder.encode(leave_type,"UTF-8")+"&"+
URLEncoder.encode("nod","UTF-8")+"="+URLEncoder.encode(nod,"UTF-8")+"&"+
URLEncoder.encode("status","UTF-8")+"="+URLEncoder.encode(status,"UTF-8")+"&"+
URLEncoder.encode("from","UTF-8")+"="+URLEncoder.encode(from,"UTF-8")+"&"+
URLEncoder.encode("to","UTF-8")+"="+URLEncoder.encode(to,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// }
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
}
}
}
Ok, I got solved my problem by creating array list for all my data then I parse then into json array and passed it as a string to php.
This is how I did:
these are my arraylist
public void approve(View view){
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
// getting data from ListAdapter class and and adding it to arraylist
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Approved");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
I have a module in my application which uses json.
The json gets updated always.
Here i want to refresh the screen as new data arrives.
Is there any method for this ?
I want to refresh the screen as new data arrives or once in every 5 seconds or something(a fixed amount of time).How to do this ?
I simply used a local json file to test this.
I just need the code for refreshing.
This is my code for json parsing :
public class MainActivity extends Activity
{
String myjsonstring;
ArrayList<Data> web = new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JsonParser();
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
}
final customtest1 adapter = new customtest1(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "Test.........", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void JsonParser()
{
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"main.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
}
}
Do this.
create a class
public class Data
{
String name ="";
String viewers ="";
public Data(String n,String v)
{
name = n;
viewers=v;
}
}
then in MainActivity create only single arraylist with type Data
ArrayList<Data> web = new ArrayList<Data>();
and then parse your json like
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
now instead of passing two array list to your custom adapter , pass only single arraylist i.e web
customtest adapter = new customtest(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
in your customtest class , inside getview when you will bind data, you will do
Data dt = web.get(position);
String name = dt.name;
String viewers = dt.viewers;
and then do what you were doing before.
and after all this, now ehnever you want to update your list simply call
adapter.notifyDataSetChanged();
your customtest class now will be like
public class customtest extends ArrayAdapter<Data>{
Context context;
int layoutResourceId;
ArrayList<Data> data = null;
public customList(Context context, int layoutResourceId, ArrayList<Data> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CustomHolder();
holder.txtName = (TextView)row.findViewById(R.id.txtName); //this is id of textview where you want to set name
holder.txtViewers = (TextView)row.findViewById(R.id.txtViewers); //this is id of textview where you want to set viewers
row.setTag(holder);
}
else
{
holder = (CustomHolder)row.getTag();
}
Data dt = data.get(postition);
holder.txtName.setText(dt.name);
holder.txtViewers.setText(dt.viewers);
return row;
}
static class CustomHolder
{
TextView txtName;
TextView txtViewers;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
new Thread(){
public void run()
{
While(true)
{
Thread.sleep(3000);
jsonParse(); //this is your method for parsing json
}
}
}.start();