This my class for network calls. Here executing a method networkCallByVolley then saving the information on shared preferences.
public class NetworkCall extends Activity {
Context context;
String res = "something";
SharedPreferences userDetails;
ArrayList<String> type = new ArrayList<String>();
ArrayList<String> value = new ArrayList<String>();
public NetworkCall(Context context){
this.context = context;
}
public void networkCallByVolley(final ArrayList<String> type, final ArrayList<String> value){
this.type = type;
this.value = value;
Log.i("type", type.toString());
Log.i("value", value.toString());
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest myReq = new StringRequest(Method.POST,
"http://My URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("rrrrr", response);
res = response;
userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("response", response);
edit.commit();
//Log.i("rrrrr", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//for(int i = 0; i<= params1.size(); i++)
for(int i =0 ; i< type.size(); i++){
params.put(type.get(i), value.get(i));
//params.put("password", "aaaaaa");
Log.i("typpppp", type.get(i));
}
return params;
};
};
queue.add(myReq);
}
public String getCharlie(){
userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
return userDetails.getString("response", "no value found");
}
public void clearCharlie(){
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.commit();
}
}
when i am trying to use this class from login activity i am getting message for the below log "pref response" is "no value found". if run it again i am getting proper response which i am expecting. I don't know how to fix this bug. any help is appreciated.
this is my main activity
public class Login extends Activity {
Button signup,submit;
EditText email,password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final NetworkCall net = new NetworkCall(getApplicationContext());
final ArrayList<String> type = new ArrayList<String>();
final ArrayList<String> value = new ArrayList<String>();
submit = (Button) findViewById(R.id.submit);
email = (EditText) findViewById(R.id.edittext_email);
password = (EditText) findViewById(R.id.edittext_pwd);
type.add("user_email");
type.add("user_password");
value.add(email.getText().toString().trim());
value.add(password.getText().toString().trim());
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
net.networkCallByVolley(type, value);
String response = net.getCharlie();
Log.i("pref resonse", response);
}
});
}
}
You need to use ASYNC task or handler.
What you are doing is calling getCharlie() method right after you made the call net.networkCallByVolley(type, value); It takes some time to get response from the sever after which only it will write the response to the shared prefrences. You are getting no result found because at that time there is no response. Respone is being calculated on some another parallel thread. As soon as that thread gets the response it show that to you but until then you will be having null. So wait for the thread to get response using ASYNC task.
#Override
public void onClick(View v) {
net.networkCallByVolley(type, value);
String response = net.getCharlie();
while(response.equalsIgnorecase("no result found")){}
Log.i("pref resonse", response);
}
Actually you need to wait until getting response from Volley.
You can use a BroadcastReceiver in your Login Activity
and send a broadcast from NetworkCall Activity after you get a response from the server, and when you receive a broadcast do what you want to do e.g checking SharedPreferences.
Alternative way you can use is Observer Pattern to get notice when you get response from server.
Related
Here iam working with web services i need to access username and password variabes from my MainActivity to MainActivity2 below is the code.
public class MainActivity extends AppCompatActivity {
String username ;
String password;
public void doLgin(View view) {
if(Build.VERSION.SDK_INT >= 10){
StrictMode.ThreadPolicy policy = StrictMode.ThreadPolicy.LAX;
StrictMode.setThreadPolicy(policy);
}
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password = ((EditText)findViewById(R.id.editTextPassword)).getText().toString();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/login.php?username=" + username + "&key=" + password);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Result", jsonarray);
String error = jsonObj.getJSONArray("Result").getJSONObject(0).toString();
String errormsg = "{\"Error\":\"Problem with authentication,Please login.\"}";
if (error.equalsIgnoreCase(errormsg)) {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("Username",username);
intent.putExtra("Password",password);
startActivity(intent);
}
}
And In my MainActivity2 class i created an object for MainActivity but it returns null values
.
You should store it on a static global class, say
public static class Credentials{
public static String USERNAME = "myUsername";
public static String PASSWORD = "myPassword";
}
Then you can access it anywhere on your project using:
Credentials.USERNAME = "setyourusername";
Credntials.PASSWORD = "setYourPassword;
But I wouldn't recommend this kind of implementation because it is really not secure, but as for an answer for your question, this probably is the approach you'll need.
Edit:
If the information should only be shared between that two activities, then #Faysal Ahmed 's answer is the way to go.
After this line on your first activity:
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password =((EditText)findViewById(R.id.editTextPassword)).getText().toString();
you can assign it directly to the static credentials class:
Credentials.USERNAME = username;
Credntials.PASSWORD = password;
then you can access it on your second activity the same way by calling Credentials.USERNAME and Credentials.PASSWORD
If you want to get the value from MainActivity then need to pass both values using putExtra.
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("username",username);
i.putExtra("password",password);
startActivity(i);
And from Main2Activity class you can get the value like this. Use this lines under onCreate method.
String user = getIntent.getStringExtra("username");
String pass = getIntent.getStringExtra("password");
No need to use MainActivity m = new MainActivity(); this line.
UPDATE:
public class Main2Activity extends AppCompatActivity {
String user;
String pass;
String JSON_URL = "http://182.18.163.39/m/list.php?username=admin&key=admin";
ListView listView;
java.util.List<List> tktList;
String link;
Button logoutbt;
Button ubt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Get value from intent that passed from previous Activity
user = getIntent.getStringExtra("username");
pass = getIntent.getStringExtra("password");
// Now you can use this two variable in any place.
logoutbt = (Button)findViewById(R.id.lbt);
logoutbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences SM = getSharedPreferences("userrecord", 0);
SharedPreferences.Editor edit = SM.edit();
edit.putBoolean("username", false);
edit.commit();
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
//initializing listview and hero list
listView = (ListView) findViewById(R.id.listView);
tktList = new ArrayList<>();
//this method will fetch and parse the data
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("Sno");
String Tktid = jsonobject.getString("TKTID");
link = jsonobject.getString("Link");
List list = new List(jsonobject.getString("Sno"), jsonobject.getString("TKTID"),jsonobject.getString("Link"));
tktList.add(list);
Log.i("website content", name);
Log.i("website content", Tktid);
Log.i("website content", link);
}
//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(tktList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
com.android.volley.RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
You can do something like this:
1) First, create a POJO class like this:
public class Info {
static Info info;
private String userName;
private String password;
public static Info getInstance() {
if (info == null) {
info = new Info();
}
return info;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName= userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password= password;
}
}
2) and then set your username and password like this:
Info.getInstance.setUserName("username");
Info.getInstance.setPassword("password");
3) and then get it like this in your other activities:
Info.getInstance.getUserName();
Info.getInstance.getPassword();
You can also pass your values to a intent and get those values in other activity.
Using the Intent you can pass the credentials through like this:
Intent i = new Intent(this, ActivityYouArePassingInformationTo.class);
i.putExtra("username", userNameValue);
i.putExtra("password", passwordValue);
Then in the activity that you want to receive the information you can get it through this way:
String userNameVal = intent.getStringExtra("username");
String passwordVal = intent.getStringExtra("password");
Now the variables in the MainActivity will have the username and password stored in a variable. Hope this helps :)
If username and password are only used in second activity only then you can pass these values in Intent.
In MainActivity
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("user_name", userName);
i.putExtra("password", password);
startActivity(i);
in Main2Activity onCreate() after setContentView() you can read data like this
Intent i = getIntent();
user = i.getStringExtra("user_name");
pass = i.getStringExtra("password");
Other ways are to save username and password in SharedPreferences in MainActivity and read Main2Activity. This might be useful when you want to auto fill previous username and password on next app launch.
There are many ways to solve this problem.
You can use below code in MainActivity class.
Intent i = new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("UserName",username);
i.putExtra("Password",password);
startActivity(i);
And in Main2Activity, you will get by using below code,
Intent i = getIntent();
String userName = i.getString("UserName");
String password = i.getString("Password");
Use below snippet code in MainActivity after you will get userName and
passsword.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("UserName", username);
editor.putString("Password", password);
editor.commit();
And after this, you will get these values in Main2Activity by below code.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
String userName = pref.getString("UserName", null);
String password = pref.getString("Password", null);
You can use static UserName and Password and get static value in other
Activity. like,
In MainActivity
public static String userName, password;
and set value after getting userName and password
userName = "abc"
password = "***"
Now In Main2Activity you will get these values directly by class name
String userName = MainActivity.userName;
String password = MainActivity.password;
You can use setter and getter method. In MainActivity, When you will find the
values you have to set userName and password.
Now, In Main2Activity you will get those values(UserName and Password) by
getter methods
I've been working on a log-in/register for an android app and have the register up and running but the log-in doesnt seem to be passing anything over to the php script via post like the register was? , I'm pretty sure the php script is fully functional as I've tested it with Postman, If anyone could point me in the right direction it would be much appreciated, Cheers
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="http://192.168.0.17/WebD/HASSAPP/login.php";
private Map<String, String> params;
public LoginRequest(String username,String password , Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
}
#Override
public Map<String,String> getParams() {
return params;
}
}
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//Edit to change title text
setSupportActionBar(toolbar);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String businessname = jsonResponse.getString("businessname");
String username = jsonResponse.getString("username");
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("businessname", businessname);
intent.putExtra("username", username);
Login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginrequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(Login.this);
queue.add(loginrequest);
}
});
}
I cannot understand how me sending via Post on my register is working fine but On Log-in it's non responsive , Log-in button does nothing , not even send me to mainactivity like the intent's purpose,
Kind Regards,
Andrew
This overriden method should be protected. You have it as public.
#Override
protected Map<String,String> getParams() {
return params;
}
Also, for debugging purposes, you might want to override the error listener as well.
How do I pass my Hashmap properly to my responseListener? Im sorry I am new in android please guide me. I have a session manager where it stores data of user so that the user may not need to login again but I am having a hard time retrieving it and having it applied in my Volley response Listener. I want to retrieve the user_id for the reason that I need it as a WHERE in my php file. I think this is simple I just dont know how to apply or convert the hashmap value. Please help me Thanks
here is my code:
The main Activity
public class SendToDatabase extends AppCompatActivity {
RatingBar ratingBar;
TextView txtRatingValue;
SessionManager session;
//Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_to_database);
//HERE IS THE SESSIONMANAGER CODE
session = new SessionManager(getApplicationContext());
HashMap<String, Integer> user_int = session.getUserLexileNID();
final Integer user_id = user_int.get(SessionManager.KEY_USER_ID);
final EditText etComment = (EditText) findViewById(R.id.etComment);
final Button bSubmit = (Button) findViewById(R.id.bSubmit);
final RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
addListenerOnRatingBar();
// addListenerOnButton();
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String comment = etComment.getText().toString();
// final int rate = ratingBar.getNumStars();
final String rate = txtRatingValue.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Toast.makeText(SendToDatabase.this,"success"+comment,Toast.LENGTH_SHORT).show();
//Intent intent = new Intent (SendToDatabase.this, CommentArea.class);
// SendToDatabase.this.startActivity(intent);
} else {
// Toast.makeText(SendToDatabase.this,"something went wrong try again later", Toast.LENGTH_SHORT).show();
// Toast.makeText(SendToDatabase.this, "There might be some problem in the server side, please try again later", Toast.LENGTH_SHORT).show();
// Toast.makeText(SendToDatabase.this, response.toString(), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
//HERE IS WHERE I NEED TO PASS MY USER_ID
CommentRateRequest commentRateRequest = new CommentRateRequest(comment, rate, user_id, responseListener);
RequestQueue queue = Volley.newRequestQueue(SendToDatabase.this);
queue.add(commentRateRequest);
}
});
}
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
txtRatingValue = (TextView) findViewById(R.id.tvRatingValue);
// if rating value is changed,
//display the current rating value in the result (textview) automatically
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
txtRatingValue.setText(String.valueOf(rating));
}
});
}}
The CommentRateRequest others calls this as their singleton class
public CommentRateRequest (String comment, String rate,int user_id Response.Listener<String>listener){
super(Method.POST, CommentRateUrl, listener, null);
params = new HashMap<>();
params.put("comment", comment);
params.put("rate", rate);
params.put("user_id", user_id+"");
// params.put("book_id", book_id+"");
}
Codes from my SessionManager:
public void createLoginSession(String Fname, String Lname, Integer user_id, Integer lexile, String role_name, String grade_name, String password){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_FNAME, Fname);
editor.putString(KEY_LNAME, Lname);
editor.putInt(KEY_USER_ID, user_id);
editor.putInt(KEY_LEXILE, lexile);
editor.putString(KEY_ROLE_NAME, role_name);
editor.putString(KEY_GRADE_NAME, grade_name);
editor.putString(KEY_PASSWORD, password);
editor.commit();
}
//Part of the tutorial dont seem to have any problem
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_FNAME, pref.getString(KEY_FNAME, null));
user.put(KEY_LNAME, pref.getString(KEY_LNAME, null));
user.put(KEY_ROLE_NAME, pref.getString(KEY_ROLE_NAME, null));
user.put(KEY_GRADE_NAME, pref.getString(KEY_GRADE_NAME, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
return user;
}
dont pay attention to this as I just forgot to add "," thanks. ..
I have MainActivity which added two fragment tab namely "tab1 and "tab2.tab 1 sends some request to server during this process I Want to show a progress dialog but when I do this through a error message "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" and also have some implementation of Broadcast receiver in tab 1 fragment which also through error "unable to register receiver"
Progress dialog code:
public class DialogUtils {
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
}
Mainactivity code:
m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
m_TabLayout.addTab(m_TabLayout.newTab().setText("Deals"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Stories"));
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
CDealMainListingPager m_oDealMainScreenPager = new CDealMainListingPager(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oDealMainScreenPager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
and tab1 fragment tab code:
public static final String TAG = CDealAppListing.class.getSimpleName();
public static final int m_TRANSACTION_SUCCESSFUL = 0;
public static String m_szMobileNumber;//declaring String mobile number variable
public static String m_szEncryptedPassword;//declaring string password variable
public static String sz_RecordCount;// //declaring String record count variable variable
public static String sz_LastCount;//declaring String lastcount variable
private static ListView m_ListView;// declaring Listview variable..
private static CDealAppListingAdapter m_oAdapter;// declaring DealListingAdapter..
public CDealAppDatastorage item;// declaring DealAppdataStorage
public View mFooter;
public AppCompatButton m_BtnRetry;
/*This Broadcast receiver will listen network state accordingly
which enable or disable create an account button*/
private final BroadcastReceiver m_oInternetChecker = new BroadcastReceiver() {// creating broadcast to receive otp sent by server from Inbox...
#Override
public void onReceive(Context context, Intent intent) {// on receive method to read OTP sent by server
changeButtonState();// check whether edit text is empty or not
}
};
RequestQueue requestQueue;
JsonObjectRequest jsonObjectRequest;
private ArrayList<CDealAppDatastorage> s_oDataset;// declaring Arraylist variable
private int[] m_n_FormImage;//declaring integer array varaible
private View m_Main;//declaring View variable
private int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
private int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
private SwipeRefreshLayout mSwipeRefresh;
private ProgressDialog m_Dialog;
private boolean bBottomOfView;
private LinearLayout m_NoInternetWarning;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
Log.i(TAG, "OnCreateView.........");
init();
return m_Main;
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume.........");
/*Registered Broadcast receiver*/
IntentFilter m_intentFilter = new IntentFilter();// creating object of Intentfilter class user for defining permission
m_intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");// action to check Internet connection
getActivity().registerReceiver(m_oInternetChecker, m_intentFilter);// register receiver....
getDetails();
}
public void changeButtonState() {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
private void getDetails() {// get details of user from shared preference...
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
if (NetworkUtil.isConnected(getActivity())) {
m_NoInternetWarning.setVisibility(View.GONE);
postDealListingDatatoServer();// here sending request in onCreate
} else {
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy...............");
getActivity().unregisterReceiver(m_oInternetChecker);// unregistaer broadcast receiver.
}
private void init() {// initialize controls
m_NoInternetWarning = (LinearLayout) m_Main.findViewById(R.id.no_internet_warning);
m_BtnRetry = (AppCompatButton) m_Main.findViewById(R.id.btn_retry);
m_BtnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retryRequest(v);
}
});
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
m_ListView.setOnScrollListener(this);
/*Swipe to refresh code*/
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.swipe);
mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/*Here check net connection avialable or not */
if (NetworkUtil.isConnected(getActivity())) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
swipeData();
}
}, 3500);
} else {
m_NoInternetWarning.setVisibility(View.VISIBLE);
mSwipeRefresh.setVisibility(View.GONE);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
}
}
});
m_n_FormImage = new int[]{// defining Images in Integer array
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
}
public void retryRequest(View v) {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
postDealListingDatatoServer();
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
/*This is new changes in code ....using Volley instead of AsynkTask*/
/*This method send request to server for deallisting*/
// this method send request to server for deal list....
public void postDealListingDatatoServer() {
try {
String json;
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
System.out.println("Record Count:-" + sz_RecordCount);
System.out.println("LastCount:-" + sz_LastCount);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.i(TAG, "Server Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity().getApplicationContext(), "Loading...");
final String m_DealListingURL = "http://202.131.144.132:8080/json/metallica/getDealListInJSON";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Server Response:-" + response);
m_Dialog.dismiss();
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == m_TRANSACTION_SUCCESSFUL) {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
s_oDataset.clear();
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
m_NoInternetWarning.setVisibility(View.GONE);
mSwipeRefresh.setVisibility(View.VISIBLE);
} else {
m_ListView.removeFooterView(mFooter);// else Load buttonvisibility set to Gone
}
}
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error:-" + error);
m_Dialog.dismiss();
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Step1: Change DialogUtils class:
public static ProgressDialog showProgressDialog(Activity activity, String message) {
ProgressDialog m_Dialog = new ProgressDialog(activity);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
Step2: Change the postDealListingDatatoServer() method.
m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Loading...");
Step3: About broadcast receiver. Please register at the onResume() method and unregister at the onPause() method.
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
m_Dialog.show();
}
return m_Dialog;
}
To dismiss dialog:
if ((m_Dialog!= null) && m_Dialog.isShowing())
m_Dialog.dismiss();
Check if fragment is visible or not.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
}
} else {
}
}
}
Here is my code... which i displayed listview data... Now i want to fetch other details under this id
I want to fetch from database based on the Growers ID. Which is get from the listview
public class FarmerDetails extends Activity implements OnClickListener
{
private TextView tv;
private Button btnView;
private TextView textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.farmerdetails);
btnView = (Button) findViewById(R.id.bView);
textViewResult = (TextView) findViewById(R.id.textViewResult);
btnView.setOnClickListener(this);
tv=(TextView) findViewById(R.id.tv1);
}
private void getData(final String value) {
Intent i = getIntent();
String code = i.getStringExtra("itemValue");
tv.setText("Grower's ID: "+code);
String url = Config.DATA_Details+tv.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FarmerDetails.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
}
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String ccri="";
String name="";
String address="";
String taluk="";
String punch = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject farmerData = result.getJSONObject(0);
ccri=farmerData.getString(Config.KEY_CCRI);
name = farmerData.getString(Config.KEY_NAME);
address = farmerData.getString(Config.KEY_ADDRESS);
taluk = farmerData.getString(Config.KEY_TALUK);
punch=farmerData.getString(Config.KEY_PUNCH);
}
catch (JSONException e)
{
e.printStackTrace();
}
textViewResult.setText("CCRI Code:\t"+ccri+"Name:\t"+name+"\nAddress:\t" +address+ "\nTaluk:\t"+taluk+"\nPunchayat:\t"+punch);
}
#Override
public void onClick(View v) {
getData();
}
}
In my code only ID is displaying... fetching is not performing.. Plz help!!
this is kinda complicated.
you'll have to check out if ur url is right. Print the url in
console and type it in some browser do the GET request. If there's
no response, well it might be your problem. Maybe you did not
compose the url right.
if there's some response in step 1, ask the server guy what's going
on there. and wait.