ListView doesn't refresh with notifydatasetchanged - android

I have a MySQL database of two columns displayed in an android ListView. I use Retrofit 1.9 to get the data from MySQL. The adapter for the ListView is a BaseAdapter and I don't have a DatabaseHelperclass. When I add a data in the ListView from my mobile phone, it doesn't refresh the ListView. I have to close and restart the app. I try to refresh with listViewAdapter.notifyDataSetChanged();.
This is the fragment where the listview is:
public class rightFragment extends Fragment {
String BASE_URL = "http://awebsite.com";
View view;
ListView listView;
ListViewAdapter listViewAdapter;
Button buttondisplay;
Button buttonadd;
EditText new_id;
EditText newWordFra;
EditText newWordDeu;
ArrayList<String> id = new ArrayList<>();
ArrayList<String> fra = new ArrayList<>();
ArrayList<String> deu = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(com.example.geeko.Deu.R.layout.fragment_right, container, false);
listView = (ListView) view.findViewById(com.example.geeko.Deu.R.id.listView); //<<<< ADDED NOTE use your id
listViewAdapter = new ListViewAdapter(getActivity(), id, fra, deu);
displayData();
buttondisplay = (Button) view.findViewById(com.example.geeko.Deu.R.id.buttondisplay);
buttonadd = (Button) view.findViewById(com.example.geeko.Deu.R.id.buttonadd);
buttondelete = (Button) view.findViewById(com.example.geeko.Deu.R.id.newID);
newWordFra = (EditText) view.findViewById(com.example.geeko.Deu.R.id.newWordFra);
newWordDeu = (EditText) view.findViewById(com.example.geeko.Deu.R.id.newWordDeu);
buttonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this , "button add", Toast.LENGTH_LONG).show();
insert_data();
listViewAdapter.notifyDataSetChanged();
}
});
buttondisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (buttondisplay.getText().toString().contains("Show")) {
listView.setAdapter(listViewAdapter);
buttondisplay.setText("Hide");
} else {
listView.setAdapter(null);
buttondisplay.setText("Show");
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
new_id.setText(id.get(position));
newWordFra.setText(fra.get(position));
newWordDeu.setText(deu.get(position));
}
});
return view;
}
public void insert_data() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();
AppConfig.insert api = adapter.create(AppConfig.insert.class);
api.insertData(
newWordFra.getText().toString(),
newWordDeu.getText().toString(),
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");
if(success == 1){
Toast.makeText(getActivity(), "Successfully inserted", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getActivity(), "Insertion Failed", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
public void displayData() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();
AppConfig.read api = adapter.create(AppConfig.read.class);
api.readData(new Callback<JsonElement>() {
#Override
public void success(JsonElement result, Response response) {
String myResponse = result.toString();
Log.d("response", "" + myResponse);
try {
JSONObject jObj = new JSONObject(myResponse);
int success = jObj.getInt("success");
if (success == 1) {
JSONArray jsonArray = jObj.getJSONArray("details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
id.add(jo.getString("id"));
fra.add(jo.getString("fra"));
deu.add(jo.getString("deu"));
}
listView.setAdapter(listViewAdapter);
} else {
Toast.makeText(getActivity(), "No Details Found", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.d("exception", e.toString());
}
}
#Override
public void failure(RetrofitError error) {
Log.d("Failure", error.toString());
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
This is the listViewAdpater class :
public class ListViewAdapter extends BaseAdapter {
private final Context context;
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> fra = new ArrayList<String>();
private ArrayList<String> deu = new ArrayList<String>();
LayoutInflater layoutInflater;
public ListViewAdapter(Context ctx, ArrayList<String> id, ArrayList<String> fra, ArrayList<String> deu) {
this.context = ctx;
this.id = id;
this.fra = fra;
this.deu = deu;
}
#Override
public int getCount() {
return id.size();
}
#Override
public Object getItem(int position) {
return id.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("ViewHolder")
#Override
public View getView(final int position, View view, ViewGroup parent) {
final Holder holder;
if (view == null) {
layoutInflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.txt_fra = (TextView) view.findViewById(R.id.fra);
holder.txt_deu = (TextView) view.findViewById(R.id.deu);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txt_fra.setText(fra.get(position));
holder.txt_deu.setText(deu.get(position));
return view;
}
static class Holder {
TextView txt_fra, txt_deu;
}
}
Should I create a method to refresh my ListView?

First of all I would suggest to remove the unnecessary initialization of your variables inside the Adapter:
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> fra = new ArrayList<String>();
private ArrayList<String> deu = new ArrayList<String>();
By assigning the pointer from your fragment you will already assign an initialized ArrayList. You want both pointers to point at the same ArrayList Object so changes apply to both.
Apparently, the data stored in the Adapter is not being updated correctly. I would suggest to debug your app - setting the breakpoint so that you can see the data that the Adapter stores after an update.
The idea of writing a method for updates has already been implemented with the notifyDataSetChanged(). Just override the method in your adapter and do eventual changes before calling the super.notifyDataSetChanged().
If you have any success with those changes let us know.

buttonadd.setOnClickListener(new View.OnClickListener() {
...
insert_data();
listViewAdapter.notifyDataSetChanged();
}
});
In your onClickListener, you are calling insert_data(), followed by listViewAdapter.notifyDataSetChanged()
insert_data() method is sending a network request to retrieve the data to populate the list. BUT, you are calling notifyDataSetChanged BEFORE the network request is done. That's why the listView is empty, and will stay empty. You need to wait AFTER the network request and AFTER you have populated your ArrayList with the data to call notifyDataSetChanged.
How do we know the network request is done? Simply at the end of the callback (which you've implemented):
new Callback<Response>() {
#Override
public void success(Response result, Response response) {...
At the end of the success method, you call listViewAdapter.notifyDataSetChanged() method.
Hope that makes sense! Try it and let us know what happens

I've founded a solution. I've added getActivity.recreate(); in the method insert_data.
public void success(Response result, Response response) {
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");
if(success == 1){
Toast.makeText(getActivity(), "Successfully inserted",
Toast.LENGTH_SHORT).show();
getActivity().recreate();
} else{
Toast.makeText(getActivity(), "Insertion Failed",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}
I'm not sure that is the best solution but it works.

Related

Scan Bar code and read it from JSON after store it in recyclerView

//1.I am trying to pass Bar code value using ZXingScannerView scanner
//2. Then if scanned bar code is equals to JSON barcode object show item_name and cost from the JSON //file inside recyclerview, My issue is after scanning nothing is showing
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
scannerView = (ZXingScannerView) view.findViewById(R.id.zxscan);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(SecondFragment.this);
scannerView.startCamera();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getActivity(), "Please Accept The Permission", Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
})
.check();
return view;
}
#Override
public void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
#Override
public void handleResult(Result rawResult) {
processRawResult(rawResult.getText());
if (Patterns.WEB_URL.matcher(rawResult.getText()).matches()) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(rawResult.getText()));
startActivity(browserIntent);
}
}
private void processRawResult(String text) {
if (text.startsWith("BEGIN:")){
String[] tokens = text.split("\n");
QRVCardModel qrvCardModel = new QRVCardModel();
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].startsWith("BEGIN:")) {
qrvCardModel.setType(tokens[i].substring("BEGIN:".length()));
}
else if (tokens[i].startsWith("N")) {
qrvCardModel.setName(tokens[i].substring("N:".length()));
}
else if (tokens[i].startsWith("ORG")) {
qrvCardModel.setOrg(tokens[i].substring("ORG:".length()));
}
else if (tokens[i].startsWith("TEL:")) {
qrvCardModel.setTel(tokens[i].substring("TEL:".length()));
}
else if (tokens[i].startsWith("URL:")) {
qrvCardModel.setUrl(tokens[i].substring("URL:".length()));
}
else if (tokens[i].startsWith("EMAIL:")) {
qrvCardModel.setEmail(tokens[i].substring("EMAIL:".length()));
}
else if (tokens[i].startsWith("ADS:")) {
qrvCardModel.setEmail(tokens[i].substring("ADS:".length()));
}
else if (tokens[i].startsWith("NOTE:")) {
qrvCardModel.setNote(tokens[i].substring("NOTE:".length()));
}
else if (tokens[i].startsWith("SUMMERY:")) {
qrvCardModel.setSummer(tokens[i].substring("SUMMERY:".length()));
}
else if (tokens[i].startsWith("DTSTART:")) {
qrvCardModel.setDtstart(tokens[i].substring("DTSTART:".length()));
}
else if (tokens[i].startsWith("DTEND:")) {
qrvCardModel.setDtend(tokens[i].substring("DTEND:".length()));
}
}
}
else if (text.startsWith("hhtp://")||
text.startsWith("hhtps://")||
text.startsWith("www."))
{
QRURLMode qrurlMode = new QRURLMode(text);
}
else if (text.startsWith("geo:"))
{
QRGeoModel qrGeoModel= new QRGeoModel();
String delims = "[ ,?q= ] +";
String tokens[]= text.split(delims);
for (int i=0; i< tokens.length;i++)
{
if (tokens[i].startsWith("geo:"))
{
qrGeoModel.setLat(tokens[i].substring("geo:".length()));
}
}
qrGeoModel.setLat(tokens[0].substring("geo".length()));
qrGeoModel.setLng(tokens[1]);
qrGeoModel.setGeo_place(tokens[2]);
}
else
{
Toast.makeText(getActivity(),"QR CODE PASS", Toast.LENGTH_SHORT).show();
String json;
try {
InputStream is = getActivity().getAssets().open("products.json");
Toast.makeText(getActivity(), "JSON1", Toast.LENGTH_SHORT).show();
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//Toast.makeText(getActivity(),"JSON2", Toast.LENGTH_SHORT).show();
json = new String(buffer, "UTF-8");
Log.d("JSONTestLogs", "JSON Raw Text: " + json);
JSONObject object = new JSONObject(json);
JSONArray productsArray = object.getJSONArray("products");
Log.d("JSONTestLogs", "Fetching the Products array from JSON File. Size: " + productsArray.length());
for (int i = 0; i < productsArray.length(); i++) {
JSONObject item = productsArray.getJSONObject(i);
Log.d("JSONTestLogs", "Item: " + i + "\n" + item.toString());
if (text.equals(item.getString("bar_code"))) {
products_name.add(item.getString("item_name"));
cost.add(item.getString("cost"));
}
}
}
catch
(IOException e)
{
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace(); }
}
scannerView.resumeCameraPreview(SecondFragment.this);
// Toast.makeText(getActivity(),"JSON3", Toast.LENGTH_SHORT).show();
}
}
after you scanned the barcode. I think add the barcode to your list here;
products_name.add(item.getString("item_name"));
After add operation, you did not refresh the recyclerview data.
This code part working just one time.
CustomAdapter customAdapter = new CustomAdapter(getActivity(), products_name, cost);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
you should call this part again or you need a function inside your adapter which is notify the data of recyclerview.

Cant access viewHolder in a customArrayadapter in another function?

I am creating an application with a list that list cards based on the value from the server.
I created a StudentCardArrayAdapter to achieve this and everything works fine. All the data has been populated in card list. also I able to get the values on button click in each card separately.
What I need is on clicking the button it will call a method requestion server for data asynchronously and get a value from the server and according to that value, i need to change the button text in that particular card.
My StudentCardArrayAdapter code:
public class StudentCardArrayAdapter extends ArrayAdapter<StudentCard> {
private static final String TAG = "CardArrayAdapter";
private List<StudentCard> cardList = new ArrayList<StudentCard>();
private Context mContext;
String selected = "0";
PreferenceHelper prefs;
CardViewHolder viewHolder;
View row;
ProgressDialog pd;
static class CardViewHolder {
TextView studentname;
TextView stop;
Button selectbutton;
CircleImageView imageId;
}
public StudentCardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(StudentCard object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public StudentCard getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.student_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.studentname = (TextView) row.findViewById(R.id.studentname);
viewHolder.stop = (TextView) row.findViewById(R.id.stop);
viewHolder.selectbutton = (Button) row.findViewById(R.id.selectbutton);
viewHolder.imageId = (CircleImageView) row.findViewById(R.id.imageId);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
StudentCard card = getItem(position);
viewHolder.studentname.setText(card.getStudName());
viewHolder.studentname.setTextColor(Color.parseColor("#000000"));
viewHolder.stop.setText(card.getStudStop());
viewHolder.stop.setTextColor(Color.parseColor("#000000"));
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
else{
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.select));
viewHolder.selectbutton.setEnabled(true);
}
final String studid = card.getStudId();
final String busname = prefs.getString("busname", "0");
final String schoolid = prefs.getString("schoolid", "");
viewHolder.selectbutton.setOnClickListener(new View.OnClickListener()
{
String updatedvalue = "0";
#Override
public void onClick(View v)
{
Log.e("studid",studid);
Log.e("busname",busname);
Log.e("schoolid",schoolid);
selectstudent(v, studid, busname, schoolid,mContext);
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Picasso.with(mContext).load(card.getImageUrl()).fit().error(R.mipmap.ic_launcher).into(viewHolder.imageId);
return row;
}
public void selectstudent(final View v, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
}
I used the below code but nothing works.. No error also.. and not change in button text.I get value of selected as 1 from server.
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
I am new to android.. and is stuck here. Please help me out.
FINALLY IT WORKED
As changes mention by Krish, I updated the code suggested by him.
And added this changes in onClick it worked
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
Change the code like this,
public void selectstudent(StudentCard card, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
card.setSelected("1");
notifyDataSetChanged();
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
and change this line like this ,
final StudentCard card = getItem(position);
and call method inside onclick.
selectstudent(card, studid, busname, schoolid,mContext);

My questions is, how do I pass the list data i have obtained from JSON in a fragment to an activity?

This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.

Methods of Fragment class in android not getting called

Hi I am a beginner for android and in my app I have to show SlidingPaneLayout at right side.
So far everything is OK.
But when I tap on SlidingPaneLayout of any row I want to reload Listview for this I wrote below code.
But here Listview is reloading by default, but when I tap on SlidingPaneLayout it's not reloading.
Below lines are not executing when I call getAllTips() method from MainActivity.
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
 ˚
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
ListViewFragment:-
public class ListViewFragment extends Fragment implements AsyncTaskClass.BackGroundServiceCall {
private ArrayList<MyTripBean> friendArrayList;
ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.listview_layout,container,false);
ListView listView = (ListView)view.findViewById(R.id.list_item);
//set ListView header:-
inflater = getActivity().getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview,listView,false);
listView.addHeaderView(header);
//adapter = new ListViewAdapter(getActivity(), R.layout.item_listview, friendArrayList);
friendArrayList = new ArrayList<MyTripBean>();
adapter = new ListViewAdapter(getActivity(),
R.layout.list_item, friendArrayList);
listView.setAdapter(adapter);
getAllTips(getActivity(),9); //Getting friendArrayList data from Services
return view;
}
// get all trips of the User
public void getAllTips(Activity activity,int tripstatus) {
try {
JSONObject json = new JSONObject();
json.put("TripStatus", tripstatus);
json.put("medicaidId", "104584743999");
if (CommonUtilities.isNetWorkStateAvailble(activity)) {
AsyncTaskClass task = new AsyncTaskClass(this, activity,
json);
task.execute(ServiceUrl.GET_ALL_TRIPS, "1",
"Token");
} else {
Log.d("==========>", "There is Network Error");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void doPostExecute(StatusObject statusObject) {
// TODO Auto-generated method stub
if (statusObject != null) {
if (statusObject.getResponseCode() == 401) {
Log.d("==========>", "Session Has been Expired");
} else if (statusObject.getResponseCode() == 200) {
handleResponseData(statusObject.getMessage());
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
}
// handle the response
public void handleResponseData(String result) {
Log.d("Final Json==========>", result);
try {
Object json = new JSONTokener(result).nextValue();
if (json instanceof JSONObject) {
// you have an object
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("Error")) {
if (jsonObject.getString("Error").equalsIgnoreCase("true")) {
if (jsonObject.has("message")) {
Log.d("==========>", "there is erorr mesage coming from server");
}
}
}
} else if (json instanceof JSONArray) {
// you have an array
handleTripsResponse(result);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// handle the json array data
public void handleTripsResponse(String result) {
try {
Type type = new TypeToken<List<MyTripBean>>() {
}.getType();
ArrayList<MyTripBean> newListData = new Gson().fromJson(result, type);
friendArrayList.addAll(newListData);
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
} catch (Throwable throwable) {
}
}
}
MainActivity:-
public class MainActivity extends AppCompatActivity {
SlidingPaneLayout mSlidingPanel;
ListView mMenuList;
String [] MenuTitles = new String[]{"First Item","Second Item","Third Item","Fourth Item"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);
}
});
}
The code looks fine. OnItemClickListeners looks fine for the listview and will work correctly.
I doubt if you are getting exception in method handleTripsResponse(). please try printing log in the catch block of this method. then you will come to know the exception and how to resolve it.
Also in your MainActivity, in onItemClickListener, do not create a new instance of the ListViewFragment, instead use the instance of fragment which you attached in fragment transaction.
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);

Pass position of the item of recycler view to open up a new acitivity

How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);

Categories

Resources