In Activity, i called web service and getting json response. Now i need to send this json response in one of the fragment of Activity. Please anyone help me how to send the json response to fragment without null value.
Thank you in advance.
public class Gifts_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refereal_activtiy);
onSucceeded();
}
private void onSucceeded() {
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject json = new JsonObject();
json.addProperty("user_id", "353");
json.addProperty("device_id", "433");
serviceClient.movie_quiz(json, callback);
}
Callback<JsonObject> callback = new Callback<JsonObject>() {
#Override
public void success(final JsonObject jsonObject, Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
///here i am getting response. i need this response in fragment .
}
});
}
#Override
public void failure(RetrofitError error) {
}
};
}
fragement:
public class Electronics_fragment extends Fragment {
Refeeral_Fragemnt.ShareAdapter adapter;
LinearLayout lay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
lay = (LinearLayout) inflater.inflate(R.layout.referralhistory, container, false);
return lay;
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//here i am getting response. i need this response in fragment .-->
//then here you can store(set) your json response value in SharedPreferences, please define SharedPreferences method globally
//and after when you call fragment retrieve(get) SharedPreferences Method in your Fragment.
}
});
Related
I am trying to get deliverycount from the server using JSONArrayRequest but I am not getting any response.PHP is fine and working but the code in android not getting the request.
Can someone please help me with this problem? I am not getting any errors in logcat also.
public class PendingDeliveryList extends Fragment {
TextView delivery_List_Count;
TextView delivered_List_Count;
String companyName,userName;
SwipeRefreshLayout mSwipeRefreshLayout;
public PendingDeliveryList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_pending_delivery_list, container, false);
delivery_List_Count=(TextView)v.findViewById(R.id.deliveryListCount);
delivered_List_Count=(TextView)v.findViewById(R.id.deliveredListCount);
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.delivery_list_count_swipe);
return v;}
#Override
public void onResume()
{
super.onResume();
userName=this.getArguments().getString("userId");
companyName=this.getArguments().getString("companyName");
String server_URL= PathUrls.pathUrl+"evs_getemployeedeliverycounts.php?db="+userName+"&userid="+companyName;
//Toast.makeText(getActivity(), "userName"+userName+"companyName"+companyName, Toast.LENGTH_SHORT).show();
//Create a volley request Object
//sample[{}]
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(server_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getActivity(), "test1", Toast.LENGTH_SHORT).show();
Log.d("pending Delivery Count",response.toString());
if (response!=null)
{
try{
delivery_List_Count.setText(response.getJSONObject(0).getString("deliverlist"));
delivered_List_Count.setText(response.getJSONObject(0).getString("deliveredlist"));
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getsInstance().getRequestQueue().add(jsonArrayRequest);
Log.d("delivery Count",server_URL);
}
}
After hours of research and deep looking into my own code, I found this simple blind error. And I am really sorry for wasting others time.
String server_URL= PathUrls.pathUrl+"evs_getemployeedeliverycounts.php?db="+companyName+"&userid="+userNAme;
I can read and write TCP/IP buffer on the Main layout and MainActivity java with a button.
But can't do so on different fragment or different layout.
ERROR MESSAGE IS:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.murat.ev.TcpClient.sendMessage(java.lang.String)' on a null object reference
My code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public TcpClient mTcpClient;
public Thread send_data;
public Button button;
public byte data[]=new byte[1024];
public DatabaseConstruction db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseConstruction(getApplicationContext());
new datasync().execute("");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1=new Fragment1();
fragmentTransaction.replace(R.id.container, fragmen1_layout);
fragmentTransaction.commit();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send_data_pre();
}
});
}
public class datasync extends AsyncTask<String, String, TcpClient>
{
#Override
protected TcpClient doInBackground(String... message)
{
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived()
{
#Override
//here the messageReceived method is implemented
public void messageReceived(String message)
{
Log.i("Debug","Input message: " + message);
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Log.i("onProgressUpdate",values[0]);
}
}
public void send_data_pre()
{
send_data = new Thread(new send_data("hello"));
send_data.start();
}
public class send_data implements Runnable
{
private String message;
public send_data (String message)
{
this.message = message;
}
#Override
public void run()
{
mTcpClient.sendMessage(message);
Log.i("Debug", "mesaj did send");
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
Button button1;
MainActivity main=new MainActivity();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
button1 =(Button)view.findViewById(R.id.buton_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
main.send_data(); ////THIS HERE IS APP STOP AND ERROR
}
});
return view;
}
}
maybe in fragment you want to do
main.send_data_pre(); insted of
main.send_data();
like you do in OnCreate() of the MainActivity if i understood your question well.
I've already searched and tried many ways on doing Intent like getActivity() / v.this / and my app still stop working when clicking this TextView to get to reserveReply class which only do simple ImageView.
---- MapFragment.class ------
#Override
public void onClick(View v) {
// I put the intent on the front of the codes just to test btw
Intent intent = new Intent(MapFragment.this, reserveReply.class);
startActivity(intent);
final String parkname = (String) v.getTag();
final String name = "Testing Test";
final String age = "21";
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("firstname",parkname);
parameters.put("lastname",name);
parameters.put("age",age);
return parameters;
}
};
requestQueue.add(request);
}
}
---- reserveReply.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation_reply);
imgReply = (ImageView)findViewById(R.id.imgReply);
imgReply.setImageResource(R.drawable.waiting);
}
}
I also tried to implement View.onClickListener in fragment but it is not working. instead use setOnClickListener method directly and do your stuff... upvote if you like it...
public class FragmentView extends Fragment implements View.OnClickListener {
TextView newsTitle;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_layout, container, false);
newsTitle = (TextView) rootView.findViewById(R.id.news_title);
newsTitle.setOnClickListener(this);
return rootView;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.news_title:
// code
break;
}
}
}
I have some tabpages and fragments. And these fragments contain a GridView element. My program is going to webservice and reading JSON data, after getting images caching and populating gridviews custom grid.
Now, how can show ProgressDialog only not completed fragments? And how can I dismiss progressDialog GridView populating will complete?
My Fragment OnCreate Method;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_b, container, false);
context = getActivity();
final ProgressDialog dialog = ProgressDialog.show(context, "", "Please wait, Loading Page...", true);
GridView gridView = (GridView) v.findViewById(R.id.gridview);
if (isConnected()) {
try {
new ProgressTask(context).execute();
gridView.setAdapter(new AdapterB(context, WallPaperList));
} catch (NullPointerException e) {
e.printStackTrace();
return v;
}
} else {
Toast.makeText(v.getContext(), "Please check your internet connection..!", Toast.LENGTH_LONG).show();
}
return v;
}
its the short example for showing progress may this help you
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
//your downloading code
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
}
}
Check this...........
public interface AsyncTaskListener<Boolean> {
public void onCompletingTask(Boolean result);
}
public class AsyncTaskGetApiKey extends AsyncTask<Void, Void, Boolean>{
ArrayList<AsyncTaskListener<Boolean>> listeners;
public AsyncTaskLoadingInSplash() {
listeners = new ArrayList<AsyncTaskListener<Boolean>>();
}
public void addListener(AsyncTaskListener<Boolean> listener){
listeners.add(listener);
}
public void removeListener(AsyncTaskListener<Boolean> listener){
listeners.remove(listener);
}
#Override
protected Boolean doInBackground(Void... params) {
//do your activities here
return true; // If everything is fine
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for (AsyncTaskListener<Boolean> listener:listeners) {
listener.onReceivingApiKey(result);
}
}
}
public class MyFagemnt extends Fragment
implements AsyncTaskListener<Boolean>{
AsyncTaskGetApiKey task;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//......
task = new AsyncTaskGetApiKey();
task.addListener(this);
//........
}
#Override
public void onCompletingTask(Boolean result) {
// your asyntask finished
// now close the progress bar
}
}
In AsyncTask, create progress dialog in onPreExecute() and dismiss that progress dialog in onPostExecute().
updated:
add this code in your viewpager activity.
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//You can get Call back to show the progress dialog when swipping.
boolean isLoading = true;//Check if the fragment is still loading or not at given position.
if (isLoading) {
//Show progress dialog.
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
In one of my project, I am using loopj asynchttpclient for communicating with my website.
The communication part working well and getting response as well
My activity looks like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebRequest test=new WebRequest();
test.callService();
}
WebRequest Class as
public class WebRequest extends Activity {
public void callService(){
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://domain.com/dp/index.php", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("P",response);
}
#Override
public void onFailure(Throwable e, String response) {
Log.v("PS",e.toString());
}
});
}
}
I am confused how to return the response to the main activity, So that I can create the listview from that response.
I am new to this
Please help me
Thanks in advance
In your WebRequest class:
I don't think you want this class to extend Activity. You should only extend Activity when you're making a page to display in your app. You just want to execute some code, so extending Activity isn't needed.
Change your call service method to be static and take an AsyncHttpClient as a parameter.
Your WebRequest class should now look like this:
final class WebRequest {
private AsyncHttpClient mClient = new AsyncHttpClient();
public static void callService(AsyncHttpResponseHandler handler) {
mClient.post("http://domain.com/dp/index.php", handler);
}
}
In your main Activity:
Now all you have to do in your main activity is call the static method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WebRequest.callService(new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// Initiated the request
}
#Override
public void onSuccess(String response) {
// Successfully got a response
}
#Override
public void onFailure(Throwable e, String response) {
// Response failed :(
}
#Override
public void onFinish() {
// Completed the request (either success or failure)
}
});
}
Do whatever you need to do with the Views in your activity in the above callbacks. Hope this Helps!