JSONArrayRequest Not Working - android

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;

Related

App crashes when fragment changes before volley response

I have bottom navigation view which has 3 fragments named Home, Notifications and Account. In Home fragment I am making volley post request that uses users last known location and on the basis of that it fetches response from the server. I want to know:
When I switch between the fragment before the volley response my app crashes and when I switch after response is complete there is no app crash.
Response from server is not showing when activity launches very first time.It shows when I switch between the fragments and come back to it again.
It is showing error log:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:138)
at android.widget.Toast.makeText(Toast.java:385)
at tiffino.app.com.Home$1.onResponse(Home.java:245)
at tiffino.app.com.Home$1.onResponse(Home.java:240)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Home.java
public class Home extends Fragment implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
com.google.android.gms.location.LocationListener {
TextView fragText;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLocation;
RequestQueue requestQueue;
StringRequest stringRequest;
public static final String TAG = "MyTag";
private static final String URL = "https://google.com";
public Home() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
fragText = view.findViewById(R.id.fragText);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
return view;
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if(mGoogleApiClient.isConnected() && requestQueue != null){
mGoogleApiClient.disconnect();
requestQueue.cancelAll(TAG);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation != null) {
String str1 = hereLocation(mLocation.getLatitude(),mLocation.getLongitude());
fragText.setText(str1);
sendLocation(str1);
}
}
#Override
public void onConnectionSuspended(int i) { }
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) { }
private void sendLocation(final String str1) {
requestQueue = Volley.newRequestQueue(getContext());
stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getActivity(),""+response,Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("name",str1);
return map;
}
};
stringRequest.setTag(TAG);
requestQueue.add(stringRequest);
}
private String hereLocation(double lat, double lon) {
String city = "";
Geocoder geo = new Geocoder(getContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = geo.getFromLocation(lat,lon,10);
if(addresses.size()>0) {
for (Address adr: addresses) {
if(adr.getLocality()!=null && adr.getLocality().length()>0) {
city = adr.getLocality();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return city;
}
}
Please let me know why app is crashing.
THANKS
The problem is probably with the getActivity() in the onRespones. The fragment isn't attached now to getActivity due to the fact that you are in another fragment now.
You can do:
if(isAdded()) {
Toast.makeText(getActivity(),""+response,Toast.LENGTH_SHORT).show();
}
letting the Activity implement the callback listeners is the most proper way to do it... because alike this one is always able to obtain the Context - no matter which Fragment is currently displayed.
public class MainActivity extends FragmentActivity implements Response.Listener, Response.ErrorListener {
...
#Override
public void onResponse(String response) {
if(response != null) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onErrorResponse(VolleyError error) {
}
}
to be called alike this (from within the Fragment):
new StringRequest(Request.Method.GET, url, getActivity());
one could still pass that String back into the current Fragment, if required.
Although, You have not provided a piece of code. But generally I can tell you that you should take care of many things when you create a web request with some callback methods.
For example suppose you have the following piece of code:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mTextView.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Set the tag on the request.
stringRequest.setTag(TAG);
// Add the request to the RequestQueue.
queue.add(stringRequest);
It really depend on the logic of your application but for example one option is to totally cancel the request when the user leaves the current fragment. Therefore you can write the following code in the onStop() of your fragment:
#Override
protected void onStop () {
super.onStop();
if (queue!= null) {
queue.cancelAll(TAG);
}
}
Another option is to check for fragment status before you try to make the changes since the user might have left the fragment when your callback method is being called:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (isResumed())
{
mTextView.setText(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (isResumed())
{
mTextView.setText("That didn't work!");
}
}
});

onPause(); for SwipeRefreshLayout not working

i have a ViewPager with 3 lists in view pager and every list have an simple SwipeRefreshLayout its working well but when RefreshLayout is reffreshing and you press the back button (onPause i think?) the program will crashed andthe error is you cant set null object i know the problem i dont know how to fix it
pls help this is my code
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.activity_fragment1,container,false);
mListView = (ListView) view.findViewById(R.id.list_news);
refresh = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
refresh.setColorSchemeColors(
R.color.material_green_200,
R.color.material_green_400,
R.color.material_green_600,
R.color.material_green_800
);
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
JsonArrayRequest request = new JsonArrayRequest(uri,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JsonParser parser = new JsonParser();
ArrayList items = parser.parseJson(response);
FlowerAdapter adapter = new FlowerAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
refresh.setRefreshing(false);
}
});
String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
JsonArrayRequest request = new JsonArrayRequest(uri,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JsonParser parser = new JsonParser();
ArrayList items = parser.parseJson(response);
FlowerAdapter adapter = new FlowerAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
return view;
}
#Override
public void onPause() {
if (refresh.isRefreshing()){
refresh.setEnabled(false);
}else {
super.onPause();
}
}
how can i override onpause method to when it called first stop refreshing then pause?
and this is compelete error Log
12-07 17:11:41.942 13992-13992/app.mma.introsliderproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.mma.introsliderproject, PID: 13992
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:73)
at app.mma.PokerInfo.twitch.TwitchFragment$2.onResponse(TwitchFragment.java:67)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is causing issue Volley.newRequestQueue(getActivity().getApplicationContext()); inside onRefresh(). You will need to check is your activity is in running state i.e is the context null or not.
#Override
public void onRefresh () {
if (YourFragment.this.isVisible()) {
String uri = "http://192.168.1.101/mySite/Flowers/flowers.json";
JsonArrayRequest request = new JsonArrayRequest(uri,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JsonParser parser = new JsonParser();
ArrayList items = parser.parseJson(response);
FlowerAdapter adapter = new FlowerAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
refresh.setRefreshing(false);
}
}
Put everything inside if(){} to avoid crash

How exactly use quickblox in android?

I take reference from official website https://quickblox.com/developers/Android#Download_Android_SDK
gradle compile succeed:
repositories {
maven {
url "https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/"
}
}
dependencies {
compile "com.quickblox:quickblox-android-sdk-core:2.5.1#aar"
compile("com.quickblox:quickblox-android-sdk-chat:2.5.1#aar") {
transitive=true
}
}
then i use the code first:
I had the APP_ID...etc
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
Second step :
I reference Guide: Getting Started with Chat API https://quickblox.com/developers/Android_XMPP_Chat_Sample#Guide:_Getting_Started_with_Chat_API
//Prepare chat service
QBChatService.setDebugEnabled(true); // enable chat logging
QBChatService.setDefaultPacketReplyTimeout(10000);//set reply timeout in milliseconds for connection's packet.
//Can be used for events like login, join to dialog to increase waiting response time from server if network is slow.
//configure chat socket
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(60); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
chatServiceConfigurationBuilder.setUseTls(true); //Sets the TLS security mode used when making the connection. By default TLS is disabled.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
It has a issue that i can't import QBChatService.ConfigurationBuilder
so i try to change gradle to compile("com.quickblox:quickblox-android-sdk-chat:2.6.1")
now QBChatService.ConfigurationBuilder can be import
Third step:
I take the official step use the code:
// Initialise Chat service
final QBChatService chatService = QBChatService.getInstance();
final QBUser user = new QBUser("garrysantos", "garrysantospass");
QBAuth.createSession(user, new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
// success, login to chat
user.setId(qbSession.getUserId());
chatService.login(user, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
}
#Override
public void onError(QBResponseException e) {
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
//To handle different connection states use ConnectionListener:
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
// connection closed on error. It will be established soon
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int i) {
}
#Override
public void reconnectionFailed(Exception e) {
}
};
QBChatService.getInstance().addConnectionListener(connectionListener);
//logOut
boolean isLoggedIn = chatService.isLoggedIn();
if (!isLoggedIn) {
return;
}
chatService.logout(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
//success
chatService.destroy();
}
#Override
public void onError(QBResponseException e) {
}
});
//By default Android SDK reconnects automatically when connection to server is lost.
//But there is a way to disable this and then manage this manually:
QBChatService.getInstance().setReconnectionAllowed(false);
when i use the step about QBChatDialog , it can't be import again....
ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(34);
occupantIdsList.add(17);
QBChatDialog dialog = new QBChatDialog();
dialog.setName("Chat with Garry and John");
dialog.setPhoto("1786");
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
//or just use DialogUtils
//for creating PRIVATE dialog
//QBChatDialog dialog = DialogUtils.buildPrivateDialog(recipientId);
//for creating GROUP dialog
QBChatDialog dialog = DialogUtils.buildDialog("Chat with Garry and John", QBDialogType.GROUP, occupantIdsList);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
}
#Override
public void onError(QBResponseException responseException) {
}
});
so i try to change gradle compile compile("com.quickblox:quickblox-android-sdk-chat:3.3.0")
now QBChatDialog can be imported.
but it has another issues...
Can't not resolve symbol 'QBSettings' and 'QBSession'
I'm angry now , are you kidding me ?
Why the official step cheat me step by step ?
I'm tired... what should i do ?
Somebody can save me please , any help would be appreciated !
According #Jagapathi kindly responding , i update my code , the next issue is that i can't log in
My toast shows Login error when i click the login button:
private void setupQuickBlox() {
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBSettings.getInstance().setAutoCreateSession(true);
//login to quickblox
String enterAccount = editAccount.getText().toString();
String enterPassword = editPassword.getText().toString();
Log.d(TAG,enterAccount);
Log.d(TAG,enterPassword);
final QBUser user = new QBUser(enterAccount, enterPassword);
//login
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser qbUser, Bundle bundle) {
SharedPreferences.Editor s = getSharedPreferences("QBid", 0).edit();
s.putString("id", user.getId().toString());
s.apply();
Log.d(TAG,user.getId().toString());
Toast.makeText(MainActivity.this, "Login success with quickblox", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(MainActivity.this, "Login error", Toast.LENGTH_SHORT).show();
}
});
}
the code is under my onCreat , so it shows Login error when i satrt the app of course , but when i enter account and password , it still shows Login error , why? I check the log , i can see the account and password that i typed , but i can't see user.getId().toString() on my log , what step is wrong ?
i check the account is correct:
Here is my key:
static final String APP_ID = "50427";
static final String AUTH_KEY = "naMGFKMshdLC3s4";
static final String AUTH_SECRET = "GP8ey4GsQXt2TGu";
static final String ACCOUNT_KEY = "dHYgix3we3bxxsvMqyuR";
Here is my test Account key:
My button onClcik:
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupQuickBlox();
}
});
Here is my log:
I can guide you with Quickblox I am in same position when I started using quickblox.
step 1:-
compile 'com.quickblox:quickblox-android-sdk-core:3.3.0#aar'
compile("com.quickblox:quickblox-android-sdk-chat:3.3.0#aar") {
transitive = true
}
This is for latest version of quickblox. So don't use old versions .
step 2:-
This is my SetUp Quickblox function you don't forgot to use app_id Auth_key auth_secret and account_key
private void SetupQuickBlox() {
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBSettings.getInstance().setAutoCreateSession(true);
//login to quickblog for
final QBUser user=new QBUser("USER_NAME OF USER","PASSWORD OF USER");
// Login
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
// success
SharedPreferences.Editor s=getSharedPreferences("QBid",0).edit();
s.putString("id",user.getId().toString());
s.apply();
Toast.makeText(HomeActivity.this, "Login succes with quickblox", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(QBResponseException error) {
// error
}
});
}
step:- 3
You are all done Login with quickblox is successful so you can now request DIALOGS or CREATE DIALOg Sessions are automatically created in latest version.
Create New Dialog
private void NewMessage() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QBChatDialog dialog = DialogUtils.buildPrivateDialog("USER_ID of other user");
dialog.setName("tester1");
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
}
#Override
public void onError(QBResponseException responseException) {
}
});
}
});
}
Request List Of Dialog Of Logged In User
I Used ListView And Dialogs result will be in array list which contains LIST of QBCHATDIALOG
private void receiveChatList() {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(100);
QBRestChatService.getChatDialogs(null, requestBuilder).performAsync(
new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(final ArrayList<QBChatDialog> result, Bundle params) {
int totalEntries = params.getInt("total_entries");
Log.wtf("chat",""+result);
TrumeMsgAdapter adapter=new TrumeMsgAdapter(TrueMeMessagesActivity.this,result);
chatlistView.setAdapter(adapter);
chatlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(TrueMeMessagesActivity.this,ChatingActivity.class).putExtra("dialog",result.get(position)));
}
});
}
#Override
public void onError(QBResponseException responseException) {
}
});
}
My Adapter Code
public class TrumeMsgAdapter extends BaseAdapter {
private ArrayList<QBChatDialog> chatlist;
private Context context;
public TrumeMsgAdapter(Context c,ArrayList<QBChatDialog> chatlist){
this.chatlist=chatlist;
this.context=c;
}
#Override
public int getCount() {
return chatlist.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View List;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
List = inflater.inflate(R.layout.trume_msg_adapter, null);
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
} else {
List = convertView;
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
}
return List;
}
}

How to send the data from activity to fragment android

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.
}
});

Can't do intent on MapFragment class to another activity class

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;
}
}
}

Categories

Resources