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);
Related
//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.
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.
I want pass my String json from fragment to another activity so make interface between fragment and activity but when lunch app get null exception from this line from my fragment :adapterCalljson.MethodCallbackjson(jsonStr);
this is my try so far :
interface class :
public interface AdapterCalljson {
void MethodCallbackjson(String jsonn);
}
fragment :
public class maghalat extends Fragment {
private View myFragmentView;
private RecyclerView recyclerView;
private DataAdapter adapter;
private String TAG = MainActivity.class.getSimpleName();
public ProgressDialog pDialog;
List<jsonContent> listcontent=new ArrayList<>();
public int dog=1;
public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
public int id;
AdapterCalljson adapterCalljson;
public String json;
public String jsonStr;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
adapterCalljson.MethodCallbackjson(json);
asyncRun();
return myFragmentView;
}
public void asyncRun(){
if(isNetworkConnected()) {
new GetContacts().execute();
} else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
jsonContent.content=c.getString("content");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
jsonContent.curpage=dog;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() {
#Override
public void MethodCallbackgo(String data) {
Integer s=null;
try {
s= Integer.valueOf(data);
}catch (NumberFormatException e)
{
}
if (s!=null && s>=1 && s<=id)
{
dog= Integer.parseInt(data);
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else
{
Toast.makeText(getActivity().getApplicationContext(),"صفحه پیدا نشد",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbacknext() {
if (dog<id)
{
dog += 1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else {
Toast.makeText(getActivity().getApplicationContext(),"این آخرین صفحه است",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbackprev() {
if (dog!=1)
{
dog-=1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else{
Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setAdapter(adapter);
json=jsonStr;
}
}
You haven't assigned an object to adapterCalljson. Assuming you're implementing AdapterCalljson in the host activity, assign it from the context onAttach:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
Firstly, your Activity containing the Fragment must implement that interface.
public class MainActivity implements AdapterCalljson {
#Override
void MethodCallbackjson(String jsonn) {
doSomethingWithJson(jsonn);
}
private void doSomethingWithJson(String json) {
}
// onCreate...
}
Next, I would recommend you create the RecyclerView outside the AsyncTask. You don't need to save the myFragmentView variable.
Additionally, you can't call the callback yet. There is no data.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maghalat, container, false);
// recyclerView = rootView.findViewById
// adapter = ...
// recyclerView.setAdadpter...
asyncRun(); // This happens in the background. There is no JSON yet
return rootView;
}
Then, perhaps you should have doInBackground return the JSON string so you don't have to store it as a class variable.
The last argument is the return type.
public class GetContacts extends AsyncTask<Void, Void, String>
So, then it is public String doInBackground(Void params...) {} and public void onPostExecute(String result) {}.
In other words, don't just return null from doInBackground
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
// Parse JSON more...
return jsonStr;
}
And then you should be able to use your callback.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}
I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}
There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again
I never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:
public class SampleAutoUpdateList extends Activity {
//Autoupdate handler
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/
try {
Log.i("UPDATE", "Handler called");
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
} catch(Exception e) {
Log.e("UPDATE ERROR", e.getMessage());
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linearmode);
this.context = this;
searchAdapter = getFeed(URL);
LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
ListView list = new ListView(context);
l2.addView(list);
// display UI
UpdateDisplay(list);
updater.run();
}
private SearchAdapter getFeed(String URL) {
try
{
SearchHandler handler = new SearchHandler();
URL url = new URL(URL);
String data = convertStreamToString(url.openStream());
data = data.substring(data.indexOf('['), data.length()-1);
handler.parseJSON(data);
return handler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
Log.e("getFeed", ee.getMessage());
return null;
}
}
private void UpdateDisplay(View searchView) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
searchList = (ListView) searchView;
myProgressDialog = ProgressDialog.show(this,
"Please wait...", "Loading search....", true);
new Thread() {
public void run() {
try{
Thread.sleep(2000);
} catch (Exception e) { }
runOnUiThread(new Runnable() {
#Override
public void run() {
if (searchAdapter == null)
{
Log.e("ERROR", "No Feed Available");
return;
}
searchAdapter.setContext(context);
searchList.setAdapter(searchAdapter);
searchList.setSelection(0);
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
}
}
And the SearchHandler class is simple:
public class SearchHandler extends DefaultHandler {
SearchAdapter _adapter;
SearchItem _item;
public SearchHandler()
{
}
public SearchAdapter getFeed()
{
return _adapter;
}
public void parseJSON(String data) {
// TODO Auto-generated method stub
_adapter = new SearchAdapter();
JSONArray parseArray;
try {
parseArray = new JSONArray(data);
for (int i=0; i < parseArray.length(); i++) {
SearchItem item = new SearchItem();
JSONObject jsonUser = parseArray.getJSONObject(i);
item.set_from(jsonUser.getString ("from"));
item.set_msg(jsonUser.getString("msg"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
No matter what I do, the handler gets called and the new items are fetched, but the list is never refreshed... Any ideas on what could be going wrong?
Well, it is a little bit difficult to follow your code, since you only have a fragment of it, and few of the really relevant bits. For example, based on your available code, your list should be forever empty, since you never associate the searchAdapter with a ListView...at least in the code you have shown.
That being said, the following lines seem particularly odd:
searchAdapter = getFeed(URL);
searchAdapter.notifyDataSetChanged();
I am going to assume that getFeed() (not shown) creates a new ListAdapter of some sort. If getFeed() is creating a new ListAdapter, there is no need to call notifyDataSetChanged() on it, as its data set hasn't changed -- it's brand new. Moreover, unless you are associating this new ListAdapter to your ListView, the new ListAdapter will have no effect.
If I'm barking up the wrong tree, consider adding lines to your sample showing the implementation of getFeed() and where you are using searchAdapter.