How to add buttons programmatically in an existing xml in Android - java

I am creating an android app that is going to host a chat with my Chatbot. I have created the Chatbot in Dialogflow and i have already integrated with android studio.
In order to create the Interface i have created three XML files.
1) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_above="#id/inputLayout"/>
<RelativeLayout
android:id="#+id/inputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#android:color/white"
android:gravity="bottom"
android:paddingBottom="9dp"
android:paddingRight="8dp"
android:paddingLeft="8dp"
android:paddingTop="8dp">
<ImageView
android:id="#+id/sendBtn"
android:layout_width="49dp"
android:layout_height="28dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/queryEditText"
android:layout_marginBottom="20dp"
android:contentDescription="This is the button to send your
message!"
android:paddingTop="4dp"
app:srcCompat="#drawable/chatbot_send_btn" />
<EditText
android:id="#+id/queryEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_toStartOf="#+id/sendBtn"
android:layout_toLeftOf="#+id/sendBtn"
android:hint="Aa"
android:imeOptions="actionSend"
android:inputType="textMultiLine"
android:paddingTop="4dp"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
Here we are creating the input EditText and the ImageView for sending the message. And then inside a scrollview, a LinearLayout chatLayout that is going to host all the chat bubbles.
2) bot_msg_layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/yo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<TextView
android:id="#+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="time"
android:textSize="13dp"
android:visibility="invisible"
/>
<LinearLayout
android:id="#+id/bot_msg_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|center_vertical"
android:layout_marginTop="12dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:background="#drawable/bot_chat_bubble"
android:gravity="start|center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/chatMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:padding="12dp"
android:text="skereeeeeeeeeeee"
android:textSize="18sp"
android:clickable="true"/>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">
</FrameLayout>
</LinearLayout>
</FrameLayout>
Here we are creating the interface for when the bot replies to the user and the answer appear to the textview.
3)user_msg_layout
Which is exactly the same as the one above but with different positioning.
Finally my MainActivity code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView sendBtn = findViewById(R.id.sendBtn);
queryEditText = findViewById(R.id.queryEditText);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage(v);
}
});
queryEditText.setOnKeyListener((view, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
sendMessage(sendBtn);
return true;
default:
break;
}
}
return false;
});
initV2Chatbot();
messageList = new ArrayList<MsgClass>();
mMessageRecycler = findViewById(R.id.recyclerview);
mMessageAdapter = new MessageListAdapter(this, messageList);
mMessageRecycler.setLayoutManager(new LinearLayoutManager(this));
mMessageRecycler.setHasFixedSize(true);
mMessageRecycler.setAdapter(mMessageAdapter);
}
private void initV2Chatbot(){
try{
//V2 api
//Initializing the chatbot from json
InputStream stream =
getResources().openRawResource(R.raw.test_agent_credentials);
GoogleCredentials credentials =
GoogleCredentials.fromStream(stream);
String projectId =
((ServiceAccountCredentials)credentials).getProjectId();
SessionsSettings.Builder settingsBuilder =
SessionsSettings.newBuilder();
sessionsClient = SessionsClient.create(sessionsSettings);
session = SessionName.of(projectId, uuid);
}
catch (Exception e){
e.printStackTrace();
}
}
private void sendMessage(View view){
//Retrieving the query written by user
String msg = queryEditText.getText().toString();
//if queryEditText is empty show the warning!
if(msg.trim().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter your query!",
Toast.LENGTH_SHORT).show();
}
else{
//adding user message
MsgClass msg_To = new MsgClass(MsgClass.FROM_USER, msg,
quickR);
messageList.add(msg_To);
int NewMsgPosition = messageList.size() - 1;
// Notify recycler view insert one new data.
mMessageAdapter.notifyItemInserted(NewMsgPosition);
// Scroll RecyclerView to the last message.
mMessageRecycler.scrollToPosition(NewMsgPosition);
// Empty the input edit text box.
queryEditText.setText("");
// Java V2 sending query to cloud
QueryInput queryInput =
QueryInput.newBuilder().setText(TextInput.newBuilder()
.setText(msg).setLanguageCode("en")).build();
new com.example.smokebot.RequestJavaV2Task(MainActivity.this,
session, sessionsClient, queryInput).execute();
}
}
public void callbackV2(DetectIntentResponse response) {
quickR.removeAll(quickR);
if(response != null){
//process aiResponse here
int responsesCount =
response.getQueryResult().getFulfillmentMessagesCount();
String botReply= "";
QuickReplies hasQuickReply;
//Checking if Fullfillment has more than one responses in
order to view them all
if(responsesCount >=2){
//Looping through Fullfillment responses
for(int i=0; i < responsesCount; i++){
Message botReplies =
response.getQueryResult().getFulfillmentMessages(i);
//Counting the text amount of each response
int TextResponseCount =
botReplies.getText().getTextCount();
for(int y=0; y < TextResponseCount; y++){
botReply += botReplies.getText().getText(y) +
"\n";
}
//checking if response contains any QuickReply
hasQuickReply =
response.getQueryResult().getFulfillmentMessages(i).getQuickReplies();
if(hasQuickReply.toString() != " "){
//counting the quick replies existing
int QuickRepliesCount =
hasQuickReply.getQuickRepliesCount();
//Looping through quickreplies to fetch them all
for (int q = 0; q < QuickRepliesCount; q++){
//Updating the list with the new QuickReplies
quickR.add(hasQuickReply.getQuickReplies(q));
System.out.println(quickR);
}
}
}
MsgClass msg_To = new MsgClass(MsgClass.FROM_BOT,
botReply, quickR);
messageList.add(msg_To);
int NewMsgPosition = messageList.size() - 1;
// Notify recycler view insert one new data.
mMessageAdapter.notifyItemInserted(NewMsgPosition);
// Scroll RecyclerView to the last message.
mMessageRecycler.scrollToPosition(NewMsgPosition);
}
//if response is only one
else{
botReply = response.getQueryResult().getFulfillmentText();
MsgClass msg_To = new MsgClass(MsgClass.FROM_BOT,
botReply, quickR);
messageList.add(msg_To);
int NewMsgPosition = messageList.size() - 1;
// Notify recycler view insert one new data.
mMessageAdapter.notifyItemInserted(NewMsgPosition);
// Scroll RecyclerView to the last message.
mMessageRecycler.scrollToPosition(NewMsgPosition);
}
}
else{
String ErrorMessage = "There was some communication issue.
Please Try again!";
MsgClass msg_To = new MsgClass(MsgClass.FROM_BOT,
ErrorMessage, quickR);
messageList.add(msg_To);
int NewMsgPosition = messageList.size() - 1;
// Notify recycler view insert one new data.
mMessageAdapter.notifyItemInserted(NewMsgPosition);
// Scroll RecyclerView to the last message.
mMessageRecycler.scrollToPosition(NewMsgPosition);
}
}
}
MessageListAdapter.java
public class MessageListAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private List<MsgClass> mMessageList;
private static final int FROM_BOT = 0;
private static final int FROM_USER = 1;
public MessageListAdapter(Context context, List<MsgClass> messageList) {
mContext = context;
mMessageList = messageList;
}
// Determines the appropriate ViewType according to the sender of the
message.
#Override
public int getItemViewType(int position) {
MsgClass msg_obj = this.mMessageList.get(position);
if (MsgClass.FROM_BOT == msg_obj.getMsgType()) {
// If the current user is the sender of the message
return FROM_BOT;
} else {
// If some other user sent the message
return FROM_USER;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
View view;
if (viewType == FROM_BOT) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.bot_msg_layout, parent, false);
return new BotMessageHolder(view);
} else if (viewType == FROM_USER) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_msg_layout, parent, false);
return new UserMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int
position) {
MsgClass msg_obj = this.mMessageList.get(position);
List<String> QR = msg_obj.getQuickR();
if(getItemViewType(position) == FROM_BOT){
BotMessageHolder botHolder = (BotMessageHolder) holder;
botHolder.bind(msg_obj.getMsgContent());
if(QR.size() != 0){
addButtons(QR, botHolder);
}
}
else{
UserMessageHolder userHolder = (UserMessageHolder) holder;
userHolder.bind(msg_obj.getMsgContent());
}
// switch (holder.getItemViewType()) {
// case FROM_BOT:
// ((BotMessageHolder)
holder).bind(msg_obj.getMsgContent());
// break;
// case FROM_USER:
//
// ((UserMessageHolder)
holder).bind(msg_obj.getMsgContent());
// default:
// break;
// }
}
#Override
public int getItemCount() {
if(mMessageList==null)
{
mMessageList = new ArrayList<MsgClass>();
}
return mMessageList.size();
}
private void addButtons(List<String> QR, BotMessageHolder botHolder){
int QRcount = QR.size();
System.out.println(QRcount);
LinearLayout ll = botHolder.bot_layout;
LinearLayout.LayoutParams layout_params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT);
layout_params.setMargins(4,4,4,4);
layout_params.gravity = Gravity.CENTER_HORIZONTAL;
// int ViewCount = ll.getChildCount();
// View v = null;
// for(int x=0; x< ViewCount; x++){
// v = ll.getChildAt(x);
// if(v instanceof Button){
// if(v.getTag().equals(1) || v.getTag().equals(2) ||
v.getTag().equals(3)){
// ll.removeView(v);
// }
// }
// }
for (int i = 0; i< QRcount; i ++){
Button qr_btn = new Button(mContext);
qr_btn.setId(i);
qr_btn.setTag(i);
qr_btn.setText(QR.get(i));
qr_btn.setBackgroundColor(Color.rgb(255,255,255));
ll.addView(qr_btn);}
}
}
UserMessageHolder.java
public class UserMessageHolder extends RecyclerView.ViewHolder {
TextView user_msg;
LinearLayout user_layout;
UserMessageHolder(View itemView) {
super(itemView);
if(itemView != null){
user_msg = itemView.findViewById(R.id.chatMessage);
user_layout = itemView.findViewById(R.id.user_msg_layout);
}
}
void bind(String message){
user_msg.setText(message);}
}
6)BotMessageHolder.java
Same but for the bot references.
The thing is that i am fetching Quick Replies from Cloud and i want to view them as Buttons in order for the user to just click them. I call the method addButtons(List QR, BotMessageHolder botHolder) to do this job inside onBindViewHolder(). the first answers appear correct like buttons but then they stack on each other. I will attach some images for you to understand what i am saying.
This one, thats the first quick replies seems fine. They are on the right bubble.
But when i scroll on the first bot message they exist there too!
And when the bot message with the next quick replies comes, it just stack onto the others and on other previous bot bubbles not just the current. Also seems everytime i am scrolling they get more.. I cannot understand..

HERE IS THE XML CODE TO ADD BUTTONS
<Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="#string/button_text"     android:drawableLeft="#drawable/button_icon"     ... />

Related

Recyclerview adapter error: Arraylist size zero in Android studio

Firstly sorry for my bad english. My issue is, I am trying to make a Weather app using Weather API. I want to show 5 day forecast using recyclerview adapter. I add the data to arraylist, that I get from API and it should go to my adapter class. It needs to show the data added to the arraylist there but it doesn't and arraylist size is always zero.
My recyclerview class is forecast
oncreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast);
Intent intent = getIntent();
Latitude = intent.getDoubleExtra("lat",0);
Longitude = intent.getDoubleExtra("long",0);
System.out.println("LATİTUDE "+Latitude+" Longitude "+Longitude);//i just experimented to
check if latitude and
longitude come
init();
}
init()
public void init(){
arrayList = new ArrayList<>();
forecast_back_icon = findViewById(R.id.forecast_back_icon);
recyclerviewforecast = findViewById(R.id.RecyclerviewForecast);
get_forecast_data(Latitude,Longitude);
forecastAdapter = new ForecastAdapter(arrayList);
recyclerviewforecast.setAdapter(forecastAdapter);
recyclerviewforecast.setLayoutManager(new LinearLayoutManager(forecast.this));
forecast_back_icon();
}
get_forecast_data() funct
public void get_forecast_data(Double Lat, Double Long){
//EXAMPLE URL
//https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API%20key}
API_KEY_FORECAST = "c29ecfafd4a70caad8fee38d6054bfc7";
URL_FORECAST = "https://api.openweathermap.org/data/2.5/onecall?lat="+Lat+"&lon="+Long+"&exclude=current,minutely,hourly,alerts&appid="+API_KEY_FORECAST;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FORECAST, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray daily = response.getJSONArray("daily");
for(int i=0;i<daily.length();i++){
String temp = daily.getJSONObject(i).getJSONObject("temp").getString("day");
String feels_like = daily.getJSONObject(i).getJSONObject("feels_like").getString("day");
String pressure = daily.getJSONObject(i).getString("pressure");
String humidity = daily.getJSONObject(i).getString("humidity");
String wind_speed = daily.getJSONObject(i).getString("wind_speed");
String icon = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("icon");
String description = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("description");
arrayList.add(new RecyclerviewModel(temp,humidity,feels_like,pressure,description,wind_speed,icon));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(request);
System.out.println("forecast class arraylist size : --> "+arrayList.size());
}
When I check at the bottom, the size of the arraylist is zero
my forecast adapter class
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.MyForecastViewHolder> {
ArrayList<RecyclerviewModel> ForecastArraylist;
public ForecastAdapter(ArrayList<RecyclerviewModel> ForecastArraylist){
this.ForecastArraylist = ForecastArraylist;
System.out.println("ForecastAdapter arraylist size : --- > "+ForecastArraylist.size());
}
#NonNull
#Override
public MyForecastViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerviewForecastRowBinding recyclerviewForecastRowBinding = RecyclerviewForecastRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
return new MyForecastViewHolder(recyclerviewForecastRowBinding);
}
#Override
public void onBindViewHolder(#NonNull MyForecastViewHolder holder, int position) {
System.out.println("we are in onbindviewholder.... ");
Double temperature = Double.parseDouble(ForecastArraylist.get(position).getTemperature()) - 273.15;
System.out.println(temperature);
Double feels_like = Double.parseDouble(ForecastArraylist.get(position).getFeels_like()) - 273.15;
holder.binding.txtRecyclerviewTemp.setText(temperature.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewFeelslike.setText(feels_like.toString().substring(0,4)+"°");
holder.binding.txtRecyclerviewHumidity.setText("%"+ForecastArraylist.get(position).getHumadity());
holder.binding.txtRecyclerviewPressure.setText(ForecastArraylist.get(position).getPressure()+"hPa");
holder.binding.txtRecyclerviewWindSpeed.setText(ForecastArraylist.get(position).getWind_speed()+"km/h");
holder.binding.txtRecyclerviewCloud.setText(ForecastArraylist.get(position).getDescription());
String icon_id = ForecastArraylist.get(position).getId();
load_weather_icon(icon_id,holder);
}
#Override
public int getItemCount() {
return ForecastArraylist.size();
}
public class MyForecastViewHolder extends RecyclerView.ViewHolder{
private RecyclerviewForecastRowBinding binding;
public MyForecastViewHolder(#NonNull RecyclerviewForecastRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public void load_weather_icon(String id,MyForecastViewHolder holder ){
int id1 = Integer.valueOf(id);
if(id1>=200 && id1 <= 232){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.thunderstorm);
}
else if(id1>=300 && id1<= 321){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=500 && id1<= 504){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.rain);
}
else if(id1 == 511){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=520 && id1<= 531){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
}
else if(id1>=600 && id1<= 622){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
}
else if(id1>=701 && id1<= 781){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.mist);
}
else if(id1 == 800 ){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.clearsky);
}
else if(id1 == 801){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.fewclouds);
}
else if(id1 == 802){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.scatteredclouds);
}
else if(id1 == 803){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
else if(id1 == 804){
holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
}
}
}
I can't see 'we are in onbindviewholder' in my forecast adapter
forecast xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".forecast"
android:orientation="vertical"
android:id="#+id/forecastLayout">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/Toolbarcities">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/toolbarconstraintforecast"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/MyToolbarforecast"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:titleTextColor="#color/white"
>
<ImageView
android:id="#+id/forecast_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/cities_back_icon"
></ImageView>
</androidx.appcompat.widget.Toolbar>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RecyclerviewForecast"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The problem here is, that you have created the adapter with an empty array list and assigned it to the Recyclerview before the Volley request is processed and the array list is filled.
There are 2 ways you can fix this. First is to create the adapter and set the adapter inside the OnResponse method of the Volley request.
Or else you can create a method in the adapter that updates the array list and notify the adapter that the dataset is changed. I hoped you'd understand this.
First is the easiest

Recyclview showing data while debug mode but not working in noraml run

I am working on android application and I am facing one problem. When I run my app then nothing showing in recycle view but when i check application in debug mode then data successfully showing in recycle view. I have checked my web service working fine and successfully giving data. How can i achieve this ?
ManageQuestionActivity,java
public class ManageQuestionActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private QuestionsListAdapter listAdapter;
private List<QuestionsItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
public static String id, message, token, encodedString;
int pageCount, totalPages;
SQLiteHandler db;
SessionManager session;
ConnectionDetector cd;
EditText edtSearch;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
edtSearch = (EditText) findViewById(R.id.edtSearch);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.questions, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "20");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
}
activity_manage_question.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
QuestionsItem.java
public class QuestionsItem {
private int id;
private String question, ansOne, ansTwo, ansThree, ansFour, answer;
public QuestionsItem() {
}
public QuestionsItem(int id, String question, String ansOne, String ansTwo, String ansThree, String ansFour, String answer) {
super();
this.id = id;
this.question = question;
this.ansOne = ansOne;
this.ansTwo = ansTwo;
this.ansThree = ansThree;
this.ansFour = ansFour;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsOne() {
return ansOne;
}
public void setAnsOne(String ansOne) {
this.ansOne = ansOne;
}
public String getAnsTwo() {
return ansTwo;
}
public void setAnsTwo(String ansTwo) {
this.ansTwo = ansTwo;
}
public String getAnsThree() {
return ansThree;
}
public void setAnsThree(String ansThree) {
this.ansThree = ansThree;
}
public String getAnsFour() {
return ansFour;
}
public void setAnsFour(String ansFour) {
this.ansFour = ansFour;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
QuestionsListAdapter.java
public class QuestionsListAdapter extends RecyclerView.Adapter<QuestionsListAdapter.ViewHolder> {
private List<QuestionsItem> timeLineItems;
String message, storyId, token, ide;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
ConnectionDetector cd;
Boolean isInternetPresent = false;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
int newPosition;
public QuestionsListAdapter(List<QuestionsItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.questios_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
token = user.get("token");
//Getting the particular item from the list
QuestionsItem item = timeLineItems.get(position);
holder.txtQues.setText(item.getQuestion());
holder.txtAnsOne.setText(item.getAnsOne());
holder.txtAnsTwo.setText(item.getAnsTwo());
holder.txtAnsThree.setText(item.getAnsThree());
holder.txtAnsFour.setText(item.getAnsFour());
holder.txtAns.setText(item.getAnswer());
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
String ques = String.valueOf(m.getQuestion());
String Option1 = String.valueOf(m.getAnsOne());
String Option2 = String.valueOf(m.getAnsTwo());
String Option3 = String.valueOf(m.getAnsThree());
String Option4 = String.valueOf(m.getAnsFour());
String answer = String.valueOf(m.getAnswer());
Intent intent = new Intent(context, UpdateQuestionActivity.class);
intent.putExtra("id", ide);
intent.putExtra("ques", ques);
intent.putExtra("option1", Option1);
intent.putExtra("option2", Option2);
intent.putExtra("option3", Option3);
intent.putExtra("option4", Option4);
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
newPosition = holder.getAdapterPosition();
ide = String.valueOf(m.getId());
alertBox();
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtQues, txtAnsOne, txtAnsTwo, txtAnsThree, txtAnsFour, txtAns, btnEdit, btnDelete;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
txtQues = (TextView) itemView.findViewById(R.id.txtQues);
txtAnsOne = (TextView) itemView.findViewById(R.id.txtAnsOne);
txtAnsTwo = (TextView) itemView.findViewById(R.id.txtAnsTwo);
txtAnsThree = (TextView) itemView.findViewById(R.id.txtAnsThree);
txtAnsFour = (TextView) itemView.findViewById(R.id.txtAnsFour);
txtAns = (TextView) itemView.findViewById(R.id.txtAns);
btnEdit = (TextView) itemView.findViewById(R.id.btnEdit);
btnDelete = (TextView) itemView.findViewById(R.id.btnDelete);
}
}
public void alertBox(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("Do you want to delete question ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Check for empty data in the form
cd = new ConnectionDetector(context);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
DeleteQuestion(token, ide);
}else {
final SweetAlertDialog alert = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Question");
alert.show();
}
private void DeleteQuestion(final String token, final String qid) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.updateQues, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
if (error) {
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
timeLineItems.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, timeLineItems.size());
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("qid", qid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
questios_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtQues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsThree"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsFour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Answer : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAns"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/btnEdit"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Edit"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
<TextView
android:id="#+id/btnDelete"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Delete"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listView.setAdapter should not be here cut
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter); // Cut from Here
And paste in this method:
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
listView.setAdapter(adapter); //Paste Here
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

How to fix position of Textview in RelativeLayout

I am having this problem where I want to fix the position of my layout. I want to fix it in the center of my layout but every time I click on EditText which makes a keyboard pop up, the TextView shifts up and I don't want that to happen. Here is my code:
comment.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:flatui="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fresco="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
android:id="#+id/comments_coordinator_layout">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/comments_appbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout_comments">
<LinearLayout
android:id="#+id/send_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<com.cengalabs.flatui.views.FlatEditText
android:fontFamily="sans-serif"
android:id="#+id/write_comment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:paddingTop="6dp"
android:paddingBottom="6dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:gravity="left"
android:textSize="16sp"
flatui:fl_theme="#array/color_primary_theme"
android:textColor="#000000"
android:cursorVisible="false"
android:hint="Comment back!"
android:background="#color/feed_bg"
android:inputType="textMultiLine"
flatui:fl_fieldStyle="fl_box"
android:scrollHorizontally="false" />
<com.cengalabs.flatui.views.FlatButton
android:fontFamily="sans-serif"
android:id="#+id/send_comment"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:textSize="16sp"
android:padding="5dp"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Send"
flatui:fl_theme="#array/color_primary_theme"
android:textAllCaps="false"
flatui:fl_textAppearance="fl_light"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/send_message"
android:id="#+id/view_comments">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/no_comments_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:visibility="gone"
android:textSize="16sp"
android:fontFamily="sans-serif"
android:text="No comments to display." />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
Comments.java:
public class Comments extends AppCompatActivity {
Post post;
private CommentsDataSource commentsDatasource;
//Local Database for storing posts
private PostsDataSource postsDataSource;
private FireBaseApplication application;
private List<Comment> commentItems;
private CommentsRecyclerViewAdapter commentsRecyclerViewAdapter;
private RecyclerView commentsView;
private TextView noCommentsView;
private Toolbar toolbar;
private LinearLayoutManager llm;
private NotificationManager notificationManager;
private boolean isNotificationActive;
private String postId;
private String tab;
private String userId;
private String posterUserId;
private String posterName;
private String postTimeStamp;
private String postStatus;
//Progress overlay
View progressOverlay;
DatabaseQuery databaseQuery;
String name;
private Firebase firebaseRef = new Firebase("https://tabsapp.firebaseio.com/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.comments);
setupActionBar();
setupActivity(savedInstanceState);
final EditText comment = (EditText) findViewById(R.id.write_comment);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//Once we send the post, we want to
comment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
comment.setCursorVisible(false);
if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
comment.setImeOptions(EditorInfo.IME_ACTION_DONE);
in.hideSoftInputFromWindow(comment.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
//Hide the cursor until view is clicked on
View.OnTouchListener onTouchListener = new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
System.out.println("Touched");
if (v.getId() == comment.getId()) {
comment.setCursorVisible(true);
}
commentsView.postDelayed(new Runnable() {
#Override
public void run() {
commentsView.smoothScrollToPosition(commentsView.getAdapter().getItemCount() - 1);
}
}, 250);
return false;
}
};
comment.setOnTouchListener(onTouchListener);
//Button for sending post
final Button button = (Button) findViewById(R.id.send_comment);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (TextUtils.isEmpty(comment.getText())) {
Toast.makeText(Comments.this, "Please enter in a comment first.", Toast.LENGTH_SHORT).show();
} else {
String text = comment.getText().toString();
Comment createdComment = new Comment("", postId, name, text, userId, getDateTime());
Toast.makeText(Comments.this, "Successfully commented.", Toast.LENGTH_SHORT).show();
comment.setText("");
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(comment.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
comment.setCursorVisible(false);
updatePost();
databaseQuery.saveCommentToFirebase(createdComment);
saveCommentInCloud(createdComment, tab);
if (noCommentsView.getVisibility() == View.VISIBLE) {
noCommentsView.setVisibility(View.GONE);
}
//Notify friends that user has posted a comment on their post. Don't get notification if you posted on your own post.
// if(!createdComment.getCommenterUserId().equals(userId)) {
// showNotification(v, commenter);
// }
}
}
});
//Now we have to show a loading bar so that we are loading the comments. While we are loading the comments, we update the comments header
populateCommentView(postId);
}
public void populateCommentView(String postId) {
commentItems = new ArrayList<Comment>();
getComments(postId);
}
private void setupActionBar() {
toolbar = (Toolbar) findViewById(R.id.comments_appbar);
setSupportActionBar(toolbar);
//Back bar enabled
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//What happens if you click back
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void updatePost(){
commentsView.postDelayed(new Runnable() {
#Override
public void run() {
commentsView.smoothScrollToPosition(commentsView.getAdapter().getItemCount());
//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
}, 1000);
}
private void checkAdapterIsEmpty () {
if(application.getCommentsRecyclerViewAdapter().getItemCount() == 1){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) noCommentsView.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.view_post);
noCommentsView.setVisibility(View.VISIBLE);
}
else {
noCommentsView.setVisibility(View.GONE);
}
}
public CommentsHeader getCommentsHeader(String id)
{
System.out.println("Going to inflate header");
CommentsHeader header = new CommentsHeader();
header.setPosterUserId(posterUserId);
header.setPosterName(posterName);
header.setPosterDate(postTimeStamp);
header.setViewStatus(postStatus);
return header;
}
public void populatePost(String id) {
TextView statusMsg = (TextView)findViewById(R.id.view_status);
System.out.println("Post: " + post);
statusMsg.setText(post.getStatus());
//Set profile picture
DraweeController controller = news_feed.getImage(userId);
SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.poster_picture);
draweeView.setController(controller);
//Set poster's name
TextView posterName = (TextView)findViewById(R.id.poster_name);
posterName.setText(post.getName());
//Set date of when post was created
TextView postDate = (TextView) findViewById(R.id.post_date);
postDate.setText(AndroidUtils.convertDate(post.getTimeStamp()));
}
public String getIntentString(String value){
Bundle extras = getIntent().getExtras();
String result = "";
if (extras != null) {
result = extras.getString(value);
}
return result;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString("postId", postId);
savedInstanceState.putString("tab", tab);
savedInstanceState.putString("userId", userId);
savedInstanceState.putString("name", name);
savedInstanceState.putString("posterUserId", posterUserId);
savedInstanceState.putString("posterName", posterName);
savedInstanceState.putString("postTimeStamp", postTimeStamp);
savedInstanceState.putString("postStatus", postStatus);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
private void setupActivity(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Restore value of members from saved state
if(savedInstanceState.containsKey("tab")) {
tab = savedInstanceState.getString("tab");
}
if(savedInstanceState.containsKey("postId")) {
postId = savedInstanceState.getString("postId");
}
if(savedInstanceState.containsKey("userId")) {
userId = savedInstanceState.getString("userId");
}
if(savedInstanceState.containsKey("name")) {
name = savedInstanceState.getString("name");
}
if(savedInstanceState.containsKey("posterUserId")) {
posterUserId = savedInstanceState.getString("posterUserId");
}
if(savedInstanceState.containsKey("posterName")) {
posterName = savedInstanceState.getString("posterName");
}
if(savedInstanceState.containsKey("postTimeStamp")) {
postTimeStamp = savedInstanceState.getString("postTimeStamp");
}
if(savedInstanceState.containsKey("postStatus")) {
postStatus = savedInstanceState.getString("postStatus");
}
} else {
postId = getIntentString("postId");
tab = getIntentString("tab");
userId = getIntentString("userId");
posterUserId = getIntentString("posterUserId");
posterName = getIntentString("posterName");
postTimeStamp = getIntentString("postTimeStamp");
postStatus = getIntentString("postStatus");
// Probably initialize members with default values for a new instance
}
databaseQuery = new DatabaseQuery(this);
application = ((FireBaseApplication) getApplication());
progressOverlay = findViewById(R.id.progress_overlay);
if(application.getName() != null && application.getName() != "") {
name = application.getName();
} else {
if(savedInstanceState != null) {
if(savedInstanceState.containsKey("name")) {
name = savedInstanceState.getString("name");
}
}
}
toolbar = (Toolbar) findViewById(R.id.comments_appbar);
notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
commentsView = (RecyclerView) findViewById(R.id.view_comments);
noCommentsView = (TextView) findViewById(R.id.no_comments_text);
llm = new LinearLayoutManager(this);
commentsView.setLayoutManager(llm);
}
}
AndroidManifest.xml:
<activity
android:name=".com.tabs.activity.Comments"
android:label="View Post"
android:configChanges="orientation|keyboardHidden"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".com.tabs.activity.Comments"
android:configChanges="orientation|keyboardHidden" />
</activity>
I have tried to set my TextView to android:gravity="center_horizontal|center_vertical" or have tried to set android:centerVertical="true" but the former produces the same exact behavior and the latter makes my TextView not even show up. Is there any way I can fix the position of the TextView? Any help would be appreciated, thanks!
Add android:windowSoftInputMode="adjustPan" in activity tag on Manifest.xml
I think configChanges flag shall be added to your manifest file ,to solve this
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
For more details read this post from developer's website
http://developer.android.com/guide/topics/resources/runtime-changes.html
You should read about the android:windowSoftInputMode property that you can add to your Activity in AndroidManifest.xml. You can read about it here: http://developer.android.com/guide/topics/manifest/activity-element.html#wsoft
You have plenty of options there, choose the one that fits your needs.
Have you tried:
android:layout_centerInParent="true" for your TextView, and use android:layout_above="#+id/view_comments"?
Untested, but TextView needs some layout parameters that relates to RelativeLayout.

Populate listview from JSONArray android

Basically this question is an update for this question
Just to rewind again, this is the country_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/gambar_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/n1"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/gambar_saja"
android:layout_toEndOf="#+id/gambar_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/code"
android:layout_below="#+id/code"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/continent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/region"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/continent"
android:layout_below="#+id/continent"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
and here is cari_studio.xml to populate the country_info into listview (listView1) :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/isiArea"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/text_selector"
android:gravity="center_vertical"
android:paddingBottom="10dp"
android:paddingLeft="35dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:text="#string/area"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="visible"/>
<Spinner
android:id="#+id/textArea"
android:layout_marginRight="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/area"
android:textColor="#color/black"
android:inputType="text"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/list_area_studio"
android:layout_below="#+id/area"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/cari_studio" android:textSize="20sp" />
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="#string/studio_hint">
<requestFocus />
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#drawable/navbar_background"
>
<RadioButton
android:id="#+id/btnAll"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_allselector"
android:text="All"
/>
<RadioButton
android:id="#+id/btnPicture"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_pictureselector"
android:text="Pictures"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnVideo"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_videoselector"
android:text="Videos"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnFile"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_fileselector"
android:text="Files"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnMore"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_moreselector"
android:text="More"
android:layout_marginLeft="5dp"
/>
</RadioGroup>
<LinearLayout
android:id="#+id/floatingmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/laysemitransparentwithborders"
android:orientation="vertical"
android:layout_marginBottom="-4dp"
android:visibility="gone"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Contacts"
android:textColor="#ffffff"
android:textSize="16dp"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ff999999"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Calendar"
android:textColor="#ffffff"
android:textSize="16dp"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
and here is the Cari Studio Class to get JSONArray result (use post) and I already success get the result :
public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cari_studio);
//Generate list View from ArrayList
new DownloadJSON().execute();
addListenerOnButton();
}
public void addListenerOnButton() {
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
radioButton1 = (RadioButton) findViewById(R.id.btnAll);
radioButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
radioButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariKelas.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
radioButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariStudio.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton4 = (RadioButton) findViewById(R.id.btnFile);
radioButton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, HotStuff.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton5 = (RadioButton) findViewById(R.id.btnMore);
radioButton5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, MyAccount.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
flexlocation = (Spinner) findViewById(R.id.textArea);
flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
runOnUiThread(new Runnable() {
public void run() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country(studio_name,address, "Website:"+ website,
"Fasilitas:"+ seo_url);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
});
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the CariStudio Class
province = new ArrayList<ProvinceModel>();
// Create an array to populate the spinner
provincelist = new ArrayList<String>();
// JSON file URL address
final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
Utils.log("url_flexlocation: " + url_flexlocation);
try {
// Locate the NodeList name
HttpGet httppost = new HttpGet(url_flexlocation);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Utils.log("data: " + data);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
ProvinceModel worldpop = new ProvinceModel();
worldpop.setId(jsonobject.optString("flex_id"));
worldpop.setProvince(jsonobject.optString("name"));
province.add(worldpop);
// Populate spinner with province names
provincelist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in cari_studio.xml
Spinner mySpinner = (Spinner) findViewById(R.id.textArea);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(CariStudio.this,
R.layout.spinner_white,
provincelist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in cari_studio.xml
TextView flexlocationid = (TextView) findViewById(R.id.isiArea);
// Set the text followed by the position
flexlocationid.setText(province.get(position).getId());
String areaid = flexlocationid.getText().toString();
Utils.log("area id:" + areaid);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(areaid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
private class CountryFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
}
the result that I got from Utils.log("daftar isi studio: " + responseAsText) :
[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]
and the result that I got from looping Utils.log("studio_name: " + studio_name) are :
studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio
It means I already got all of it use looping.
But the problem is the result did not populate into listview (it show as one one last result NF Studio, the other did not appear).
What I need is populate this into 4 texview from country_info (I disable imageview) :
String studio_name, address, website, seo_url
What is the correct code to show/populate that into listview?
Add the values into a List and pass it to the Adapter class of your ListView inside onPostExecute()
You don't need a thread, that's the whole point of async.
List View code is in the for loop
UI code belongs to PostExecute() not doInBackground()
You reinitialized the list inside of the loop
Try like this:
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
private ArrayList<Country> countryList = new ArrayList<Country>();
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
countryList.add(country);
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}

ArrayAdapter never used ArrayList null and all items appear in single row

I am new to android and I am trying to create a list view using an array adapter, a run method and multi threading. The list displays all the data from an array list as a single row.
My MainActivity looks like this:
public class MainActivity extends FragmentActivity implements OnClickListener{
..
ArrayList<StorylineData> storylineData;
ArrayList<SummaryData> summary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerAPI = (Spinner) findViewById(R.id.spinnerAPI);
mButtonSubmit = (Button) findViewById(R.id.buttonSubmit);
mEditTextResponse = (ListView) findViewById(R.id.editResponse);
mProgressRequest = (ProgressBar) findViewById(R.id.progressRequest);
mButtonSubmit.setOnClickListener(this);
...
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
case 0: // Authenticate
...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
...
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", "20140714T073812Z", false);//Date changed to "20150418" "null changed to"20140714T073812Z"
break;
...
toggleProgress(false);
break;
}
}
...
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
updateResponse(
"Date:\t" + result.get(0).getDate() + "\n"
+ "-----------Activity 1 Summary--------\t" + "\n"
+ "Activity:\t" + result.get(0).getActivity().toString() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Activity 2 Summary---------\t" + "\n"
+ "Activity:\t" + result.get(0).getSummary().get(0).getActivity() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Segments---------\t" + "\n"
+ "Type:\t" + result.get(0).getSegments().get(0).getType() + "\n"//returns 1587 with .getCaloriesIdle()
...
}
public void updateResponse(final String message) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mButtonSubmit.setText(message);
StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, storylineData);
mEditTextResponse.setAdapter(adapter);
}
});
}
}
My ArrayAdapter class looks like this:
public class StorylineAdapter extends ArrayAdapter<SummaryData>{
private Context context;
private Runnable runnable;
private ArrayList<StorylineData> storylineData;
public StorylineAdapter(Context context, int resource, ArrayList<SummaryData> objects) {
super(context, resource, objects);
this.context = context;
this.runnable = runnable;
this.summary = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_storyline, parent, false);
//Display in the TextView widget
SummaryData summary1 = summary.get(position);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText(summary1.getActivity());
return view;
}
}
Here is my parser class:
public class StorylineData extends ArrayList<StorylineData> {
...Getters/Setters...
/**
* Parse a {#link org.json.JSONObject} from storyline {#link org.json.JSONArray}, then return the corresponding {#link StorylineData} object.
*
* #param jsonObject : the storyline JSON object received from server
* #return corresponding {#link StorylineData}
*/
public static StorylineData parse(JSONObject jsonObject) throws JSONException {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
/**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/
JSONArray summariesJsonArray = jsonObject.optJSONArray("summary");
if (summariesJsonArray != null)
for (int i = 0; i < summariesJsonArray.length(); i++) {
/**each time through array will need to get a reference of current object*/
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
/**===============Translate data from json to Java=================*/
/**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/
ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop
storylineData.setSummary(summary);
/**Get summary from json into java*/
summariesJsonArray.getJSONObject(i).getString("distance");
/**Get date from json into java*/
String date = summaryJsonObject.optString("date");
storylineData.setDate(date);
/**Get group from json into java*/
String group = summaryJsonObject.optString("group");//Get name using key e.g. date
storylineData.setGroup(group);
...
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n");
System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance"));
System.out.println("print summary" + summaryJsonObject);
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop
storylineData.setSegments(segments);
String type = segment.optString("type");
storylineData.setType(type);
...
storylineData.segments.add(SegmentData.parse(segment));
Log.d("StorylineDataCls \t sSo", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
I'm wondering if the reason the items are appearing in a single row may be because of a problem in the layout files?
Main Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:id="#+id/spinnerAPI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/API_Names"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Data"
android:layout_below="#+id/spinnerAPI"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressRequest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editResponse"
android:layout_below="#+id/spinnerAPI"
android:layout_alignLeft="#+id/progressRequest"
android:layout_alignStart="#+id/progressRequest" />
</RelativeLayout>
Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:text="#string/flower_name_placeholder"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Changed MainActivity to implement View.OnClickListener:
public class MainActivity extends FragmentActivity implements View.OnClickListener {
Removed ArrayAdapter and replaced updateResponse method with:
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
//MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
ListView mListView = (ListView) findViewById(R.id.list_view);
String[] stringArray = message.split("\n");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, stringArray);
mListView.setAdapter(adapter);
}
});
}

Categories

Resources