I have made a discussion forum where the person who is logged in can ask a question and the main forum shows all the question put up by a different user. everyone can answer the question also and rate.
The problem is when is add the question from adding question activity it is going back to discussion forum but not refreshing. What I want is as soon as the question is asked, it should show in the discussion forum and the user should have the ability to modify and delete that question. everything is dynamic how to delete the dynamic data as well.
this is my discussion forum code
package com.example.pitechnologies.pkguru.fragment;
public class DiscussionForumFragment extends Fragment {
TextView title;
RelativeLayout askquestion;
public View view;
UserProfileData userProfileData;
String U_id;
EditText que, desc;
TextView btnask;
String uname;
LinearLayout linearLayout;
ImageView imgSpoon;
final List<Model_Forum> unilist = new ArrayList<>();
private static String TAG = DiscussionForumFragment.class.getSimpleName();
private RecyclerView forumrecyclerView;
private ForumList_Adapter forumAdapter;
public DiscussionForumFragment() {
}
#Override
public void onStart() {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
// forumdata();
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity) getActivity()).getSupportActionBar().show();
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
title = (TextView) view.findViewById(R.id.forumtitle);
title.setText("DISCUSSION FORUM");
askquestion = (RelativeLayout) view.findViewById(R.id.askquestion);
askquestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(PreferenceHelper.getInstance(getActivity()).getSemid() == null) {
Intent intent = new Intent(getActivity(), ActivityLoginSignUp.class);
startActivity(intent);
}else {
Intent intent = new Intent(getActivity(), ActivityQuestionaire.class);
intent.putExtra("uu_id", U_id);
startActivity(intent);
}
}
});
forumrecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_forum);
forumrecyclerView.setHasFixedSize(true);
forumrecyclerView.setLayoutManager(new LinearLayoutManager(DiscussionForumFragment.this.getActivity()));
forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);
forumrecyclerView.setNestedScrollingEnabled(false);
imgSpoon = (ImageView) view.findViewById(R.id.image_spoon);
linearLayout = (LinearLayout) view.findViewById(R.id.pg_loader);
linearLayout.setVisibility(View.INVISIBLE);
forumdata();
return view;
}
public void forumdata() {
unilist.clear();
/* final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();*/
linearLayout.setVisibility(View.VISIBLE);
ObjectAnimator flip = ObjectAnimator.ofFloat(imgSpoon, "rotationY", 0f, 180f);
flip.setDuration(800);
flip.setRepeatCount(Animation.INFINITE);
flip.start();
StringRequest strReq = new StringRequest(Request.Method.POST,
URLconstant.FORUM, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject data = new JSONObject(response);
Log.d("data", data.toString());
JSONArray datarray = data.getJSONArray("data");
for (int i = 0; i < datarray.length(); i++) {
JSONObject secondobj = datarray.getJSONObject(i);
Log.d("secondobj", secondobj.toString());
Model_Forum model_forum = new Model_Forum();
model_forum.mforum_id = secondobj.getString("forum_id");
model_forum.mqst = secondobj.getString("qst");
model_forum.mqst_description = secondobj.getString("qst_description");
model_forum.mqst_uid = secondobj.getString("qst_uid");
model_forum.muser_id = secondobj.getString("user_id");
model_forum.mfullname = secondobj.getString("fullname");
model_forum.muniver_id = secondobj.getString("univer_id");
model_forum.mbranchid = secondobj.getString("branchid");
model_forum.msemid = secondobj.getString("semid");
model_forum.mcollegeid = secondobj.getString("collegeid");
model_forum.muser_image = secondobj.getString("user_image");
model_forum.mq_date = secondobj.getString("q_date");
model_forum.mq_time = secondobj.getString("q_time");
unilist.add(model_forum);
}
if (getContext() != null) {
/* forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);*/
forumAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(strReq);
}
Related
help guys how to display image without using a button, I tried to put it on create but not working and I tried to make it as a function but still not working,but when in button (on click) it show image. I want to show the image without clicking the button.
I want to load the image without clicking the button, so when the user come the image automatically load without push of a button.
public class MainActivity extends AppCompatActivity {
TextView textViewdatashow;
EditText editTextvalue;
ImageView imageView;
Button buttonfetch;
String url ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewdatashow = (TextView) findViewById(R.id.tvshowdata);
editTextvalue = (EditText) findViewById(R.id.etvalue);
imageView = (ImageView) findViewById(R.id.image);
buttonfetch = (Button) findViewById(R.id.buttonfetchdata);
buttonfetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextvalue.getText().toString();
url = "https://PASTE_YOUR_IMAGE_URL"+id+".jpg";
getData();
}
});
}
private void getData() {
String id = editTextvalue.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Check Detail!", Toast.LENGTH_LONG).show();
return;
}
String url = Config.DATA_URL + editTextvalue.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSONS(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSONS(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewdatashow.setText("" + name);
ImageRetriveWithPicasso();
}
private void ImageRetriveWithPicasso() {
Picasso.get()
.load(url)
.placeholder(R.drawable.imageholder)
.into(imageView);
}
}
Put this code inside on create view
final Handler myHandler = new
Handler(Looper.getMainLooper());
new Thread(new Runnable() {
#Override
public void run() {
myHandler.post(new Runnable() {
#Override
public void run() {
getData()
}
});
}
})).start();
}
I have a videoview and listview/gridview in my playvideo activity.
One video is already playing in the videoview. But now i want to play the other video which are showing in the listview/gridview how can i do that?
Playvideo Activity
public class playvideoactivity extends Activity {
GridViewWithHeaderAndFooter grid;
String videourl="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
private static final String url = "http://dakwf.org/api/bd_english.json";
private List<ChannelItem> chanellist = new ArrayList<ChannelItem>();
private static final String TAG = MainActivity.class.getSimpleName();
public static VideoView player;
public static ImageButton btnPlayPause;
private ImageView btnFullscreen;
private ProgressBar spinner;
private RelativeLayout mediaController;
private Handler btnHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar) findViewById(R.id.progressBar);
player=(VideoView) findViewById(R.id.player);
mediaController=(RelativeLayout) findViewById(R.id.media_controller);
spinner.setVisibility(View.VISIBLE);
mediaController.setVisibility(View.INVISIBLE);
btnPlayPause=(ImageButton) findViewById(R.id.btn_playpause);
btnFullscreen=(ImageView) findViewById(R.id.btn_fullscreen);
final CustomGridviewadapter customGridview= new CustomGridviewadapter(this,chanellist);
grid = (GridViewWithHeaderAndFooter) findViewById(R.id.grid_view);
setGridViewHeaderAndFooter();
grid.setAdapter(customGridview);
//----------- Creating volley request obj--------------------
JsonArrayRequest movieReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ChannelItem item = new ChannelItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
// adding movie to movies array
chanellist.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
customGridview.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
//------------------- Mediacontroller Visiblity-------------------------------------
player.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(final View paramAnonymousView, MotionEvent paramAnonymousMotionEvent)
{
if (paramAnonymousMotionEvent.getAction() == 0){
if (MainActivity.this.mediaController.getVisibility() != View.INVISIBLE) {
}
MainActivity.this.mediaController.setVisibility(View.VISIBLE);
MainActivity.this.btnHandler.postDelayed(new Runnable(){
public void run(){
MainActivity.this.mediaController.setVisibility(View.INVISIBLE);
}
}, 2000L);
}
for (;;){
return true;
}
}
});
//------FullScreen Button -----
btnFullscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView) {
Intent i = new Intent(MainActivity.this, FullScreenView.class);
startActivity(i);
}
});
//------Play Pause Button ----------
btnPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView){
if ( (player != null) && (MainActivity.this.player.isPlaying()) ){
MainActivity.this.player.pause();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_play);
return;
}
MainActivity.this.player.start();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_pause);
return;
}
});
//----------------------------------------
try {
MediaController mController = new MediaController(MainActivity.this);
mController.setAnchorView(player);
Uri video = Uri.parse(videourl);
player.setMediaController(mController);
player.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
player.setMediaController(null);
player.requestFocus();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
player.start();
hidespinner();
}
});
}
// ------------ Header Gridview ----------------
#SuppressLint({"InflateParams", "SetTextI18n"})
private void setGridViewHeaderAndFooter() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.grid_header, null, false);
//locate views
TextView headerText = (TextView)headerView.findViewById(R.id.textViewheader);
headerText.setText("Suggestion");
headerView.setOnClickListener(onClickListener(0));
grid.addHeaderView(headerView);
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
// Toast.makeText(MainActivity.this, "Header Clicked!", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(MainActivity.this, "Footer Clicked!", Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
hidespinner();
}
private void hidespinner() {
if (spinner != null) {
spinner.setVisibility(View.INVISIBLE);
spinner = null;
}
}
}
When opening starting the app you need to get the data and store on a variable or into database.
Create a ChannelList type List (List<ChannelList>) and store ChannelList data into it.
List<ChannelList> list = new ArrayList<>(); // containing all data
You can store Title, VideoUrl, iconUrl and add it to the list.
When clicking on a List Item you will get the position by using setOnItemClickListener.
And then use the position to get the clicked ChannelList position.
Suppose your list type variable is channelList.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChannelList channelList= list.get(position);
// now you have all data of clicked ChannelList
// do whatever you like
//channelList.getVideoUrl(); etc as your getter method
}
}
});
For more about List, you can check it Here
This question already has answers here:
How to save custom ArrayList on Android screen rotate?
(4 answers)
Closed 6 years ago.
I have an ArrayList with custom json objects fetched from the web with Volley. I would like to be able to save and restore these objects on a screen rotate. I would also like to save and restore my current scrolled position on screen rotate.
I have a sketchy idea that this can be done with onSaveInstanceState and onRestoreInstanceState?
Activity Code
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of posts
private List<PostItems> mPostItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.post_recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the postlist
mPostItemsList = new ArrayList<>();
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_posi, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_nega, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
Thanks in advance.
Note a duplicate of How to save custom ArrayList on Android screen rotate?. While the arraylist in that question is declared in the Activity, mine is fetched with volley from the web. I don't know how to implement it for my arraylist, else this question wouldn't be asked
This is, in fact, a duplicate of the post you mentioned. Yes, the list was declared in the activity's onCreate() in that post, whereas you are doing it asynchronously. However, the idea is the same.
Once you have data to send, at any point of your application, it can be saved and restored.
The key, in your case, is to not call getData() every time the device is rotated. If you already have data loaded in mPostItemsList, then save and restore it via onSaveInstanceState(), and in onCreate() you get the data from the saved state. If that data does not exist, then you call getData().
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String KEY_POST_ITEMS = "#postitems";
//Creating a list of posts
private List<PostItems> mPostItemsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)){
mPostItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
} else {
//Initializing the postlist
mPostItemsList = new ArrayList<>();
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
showNoNetworkDialog();
}
}
mAdapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
}
private void parseData(JSONArray array){
mPostItemsList.clear();
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
mAdapter.notifyDataSetchanged();
}
Edit: I didn't see the requirement to save scroll position. Look at Emin Ayar's answer for that. Also, a similar answer for it is also here: How to save recyclerview scroll position.
You can use onConfigurationChanged at your activity to detect rotation changes. Also you should track lastVisibleItemPosition with layoutManager.findLastVisibleItemPosition() and when rotation changed you should scroll to this position. You will need to use recyclerView.setOnScrollListener() to listen scrolls to keep your lastVisibleItemPosition updated
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating and initializing list of posts
private List<PostItems> mPostItemsList = new ArrayList<>();;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
private int lastVisibleItemPos = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data and check if postList have value set before or not
// because this part will be called on every rotation change, we are controlling this
if (mPostItemsList.size() <= 0) {
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.post_recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
getData();
}
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_posi, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_nega, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// set your adapter here with your data
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
I need to put a 30sec timer in my otp verfication page after 30secs timer should be gone and the keyboard should pop up. what needs to be done??
Below are my java files.
SignUpFragment.java
SignUpActivity activity;
/**
* Declaring Variables for Views
*/
TextView SignupAlreadyMember;
EditText SignUpName, SignUpEmail,referCode;
Button SignUpRegister;
VirtualApplication virtualApplication;
// Progress dialog
private ProgressDialog pDialog;
public SignUpFragment() {
}
#Override
public void onAttach(Activity activit) {
super.onAttach(activit);
this.activity = (SignUpActivity) activit;
virtualApplication = (VirtualApplication) activity.getApplicationContext();
}
int bodyId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bodyId = getArguments().getInt("output");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
activity.setTempTitle("signup");
inItViews(view);
SignUpRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterUser();
// showVerifyMobileScreen(123);
}
});
SignUpEmail.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
RegisterUser();
}
return false;
}
});
SignupAlreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gotoLoginScreen();
}
});
return view;
}
private void gotoLoginScreen() {
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
activity.finish();
}
public boolean validCellPhone(String number) {
return Patterns.PHONE.matcher(number).matches();
}
private void RegisterUser() {
String email = SignUpEmail.getText().toString().trim();
String name = SignUpName.getText().toString().trim();
String code=referCode.getText().toString().trim();
if (email.isEmpty() ||!SystemUtil.isValidMobile(email)) {
SignUpEmail.setError("Enter Mobile number here");
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phone_number", email);
jsonObject.put("body_id", bodyId);
jsonObject.put("referral_code",code);//referral_code
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
jsonObject.put("imei", SystemUtil.getIMEINumber(activity, tm)) ;
} catch (JSONException e) {
e.printStackTrace();
}
SignUpRegister.setEnabled(false);
requestForRegistration(jsonObject);
}
private void requestForRegistration(JSONObject jsonObject) {
showpDialog();
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, AppConstants.REGISTER_URL, jsonObject, this, this);
customJSONObjectRequest.setTag("Register");
customJSONObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
customJSONObjectRequest.setShouldCache(true);
requestQueue.add(customJSONObjectRequest);
//
}
private void showVerifyMobileScreen(int userId) {
VerificationFragment verificationFragment = new VerificationFragment();
Bundle bundle = new Bundle();
bundle.putInt("userId", userId);
bundle.putString("mobile", SignUpEmail.getText().toString().trim());
verificationFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, verificationFragment).commit();
}
private void inItViews(View view) {
TextView SignUPHeader = (TextView) view.findViewById(R.id.SignUPHeader);
TextView Signupmessage= (TextView) view.findViewById(R.id.Signupmessage);
Signupmessage.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUPHeader.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignupAlreadyMember = (TextView) view.findViewById(R.id.SignupAlreadyMember);
SignupAlreadyMember.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpName = (EditText) view.findViewById(R.id.SignUpName);
SignUpName.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpEmail = (EditText) view.findViewById(R.id.SignUpEmail);
SignUpEmail.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpRegister = (Button) view.findViewById(R.id.SignUpRegister);
SignUpRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
referCode = (EditText) view.findViewById(R.id.referCode);
referCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
SignUpRegister.setEnabled(true);
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
SystemUtil.sysOut("register::::: " + jsonObject.toString());
if (JSONUtil.readBoolean(jsonObject, "status")) {
int userId = JSONUtil.readInt(jsonObject, "user_id");
showVerifyMobileScreen(userId);
}else{
SignUpRegister.setEnabled(true);
}
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
}
VerificationFragment.Java
SignUpActivity activity;
TextView verifyTitleOne, verifyTitleTwo, verifyChnageNumber, verificationResend;
EditText SignUpMobile, VerficationCode;
Button VerificationRegister;
int userId;
String mobile;
boolean isResend;
public VerificationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
userId = bundle.getInt("userId");
mobile = bundle.getString("mobile");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verfication, container, false);
activity.setTempTitle("details");
inItViews(view);
SignUpMobile.setText("" + mobile);
VerificationRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!VerficationCode.getText().toString().trim().isEmpty()) {
Toast.makeText(activity, "Verifying", Toast.LENGTH_LONG).show();
showpDialog();
getDefaultData();
} else {
VerficationCode.setError("Enter Code");
}
}
});
verificationResend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isResend) {
isResend = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject, AppConstants.RESEND_OTP_URL);
}else
Toast.makeText(activity,"Please Wait",Toast.LENGTH_SHORT).show();
}
});
// setvalues();
return view;
}
private void setvalues() {
VerficationCode.setText("51692");
VerificationRegister.performClick();
}
private void getDefaultData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", userId);
jsonObject.put("token", VerficationCode.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject,AppConstants.VERIFY_NUMBER_URL);
}
private void requestServer(JSONObject jsonObject, String url) {
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, this, this);
customJSONObjectRequest.setTag("verify");
requestQueue.add(customJSONObjectRequest);
}
private void gotoSelectSizesPage(JSONObject jsonObject) {
Bundle bundle = new Bundle();
bundle.putString("output", jsonObject.toString());
DoneFragment homeKitFragment = new DoneFragment();
homeKitFragment.setArguments(bundle);
activity.setTempTitle("");
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeKitFragment).commit();
}
private void inItViews(View view) {
verifyTitleOne = (TextView) view.findViewById(R.id.verifyTitleOne);
verifyTitleOne.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyTitleTwo = (TextView) view.findViewById(R.id.verifyTitleTwo);
verifyTitleTwo.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyChnageNumber = (TextView) view.findViewById(R.id.verifyChnageNumber);
verifyChnageNumber.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verificationResend = (TextView) view.findViewById(R.id.verificationResend);
verificationResend.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpMobile = (EditText) view.findViewById(R.id.SignUpMobile);
SignUpMobile.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerficationCode = (EditText) view.findViewById(R.id.VerficationCode);
VerficationCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerificationRegister = (Button) view.findViewById(R.id.VerificationRegister);
VerificationRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], "3gpp");
smsMessageStr = smsMessage.getMessageBody().toString();
// String address = smsMessage.getOriginatingAddress();
/*smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";*/
}
VerficationCode.setText("" + stripNonDigits(smsMessageStr));
VerificationRegister.performClick();
}
}
};
private ProgressDialog pDialog;
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
public static String stripNonDigits(
final CharSequence input) {
final StringBuilder sb = new StringBuilder(
input.length());
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c > 47 && c < 58) {
sb.append(c);
}
}
return sb.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (SignUpActivity) activity;
activity.registerReceiver(broadcastReceiver, new IntentFilter(
AppConstants.BROADCAST_ACTION_SMS));
}
#Override
public void onDetach() {
super.onDetach();
activity.unregisterReceiver(broadcastReceiver);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
isResend=false;
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
if (JSONUtil.readBoolean(jsonObject, "status") &&jsonObject.has("user_data")) {
gotoSelectSizesPage(jsonObject);
}
}
}
Here is my main activity Collegelist with the contents already loaded from the database but i have only displayed the name.When i click on the name i want to show the name,address and contact on different activity.
public class Collegelist extends ActionBarActivity {
HTTPConnection http;
List<Colleges> college = new ArrayList<Colleges>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.college_list);
http = new HTTPConnection(getApplicationContext());
if (http.isNetworkConnection()) {
//String data = http.HTTPGetData("http://localhost/minorproject/show.php");
//Toast.makeText(getApplicationContext(),data ,Toast.LENGTH_LONG).show();
task.execute();
}
else {
Toast.makeText(getApplicationContext(), "check your connection",
Toast.LENGTH_LONG).show();
}
}
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String data = http.HTTPGetData("http://localhost/college/show.php");
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
populateList(result);
displayList();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
};
protected void populateList(String result) {
try {
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
JSONObject jobj = new JSONObject(result);
String res = jobj.getString("success");
if (!res.equals("true")) {
Toast.makeText(getApplicationContext(), "JSON Error",
Toast.LENGTH_LONG).show();
return;
}
else
{
JSONArray data = jobj.getJSONArray("msg");
// Toast.makeText(getApplicationContext(),"successss",Toast.LENGTH_SHORT).show();
for (int i = 0; i < data.length(); i++) {
JSONObject col = data.getJSONObject(i);
Colleges cg = new Colleges(col.getString("cname"), col.getString("caddress"), col.getString("ccontact_a"));
college.add(cg);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
protected void displayList() {
ArrayAdapter<Colleges> adapter = new ArrayAdapter<Colleges>(this, R.layout.list_item,college){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.list_item,null);
//set values
Colleges c = college.get(position);
((TextView)view.findViewById(R.id.name)).setText(c.getName());
/* ((TextView)view.findViewById(R.id.address)).setText(c.getAddress());
((TextView)view.findViewById(R.id.contact)).setText(c.getContact());
*/
return view;
}
};
final ListView collegelistnew = (ListView) findViewById(R.id.listView);
collegelistnew.setAdapter(adapter);
collegelistnew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
/*Toast.makeText(
getApplicationContext(),
"You clicked position" + position + "with item name"
+ college.get(position).getName(),
Toast.LENGTH_LONG).show();*/
Intent newIntent =new Intent(getApplicationContext(),CollegeDetails.class);
newIntent.putExtra("college", (Serializable) college.get(position));
startActivity(newIntent);
}
});
}}
Uncomment these two lines :
/* ((TextView)view.findViewById(R.id.address)).setText(c.getAddress());
((TextView)view.findViewById(R.id.contact)).setText(c.getContact());
*/
Then set their visibility to GONE using:
((TextView)view.findViewById(R.id.address)).setVisibility(View.GONE);
((TextView)view.findViewById(R.id.contact)).setVisibility(View.GONE);
or using xml.
And in this way you can show only one name in your list view but you get the address and contact also to carry on to another activty.
That class seems to be OK. However you should make your class Collegesto implement Parcelableinterface.
The error must be in CollegeDetails class