Activity ActionBar is invisible in fragment - java

I have problem with ActionBar in my fragment. It's invisible in it, so I can't execute getActionBar().setDisplayHomeAsUpEnabled(true); in my SignUpActivity.java. In every other Activity (not Fragment) it's visible.
Could You tell me what I am doing wrong? Probably something is missing.
fragment_sign_up.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:context="com.msh.organizer.SignUpActivity">
<EditText
android:layout_below="#id/toolbar"
android:id="#+id/nickname_et"
android:hint="#string/nickname"
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/email_et"
android:hint="#string/mail"
android:layout_marginTop="5dp"
android:layout_below="#id/nickname_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/password_et"
android:hint="#string/password"
android:inputType="textPassword"
android:layout_marginTop="5dp"
android:layout_below="#id/email_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/sign_up_btn"
android:layout_marginTop="15dp"
android:layout_below="#id/password_et"
android:text="#string/sign_up"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
activity_sign_up.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />
SignUpActivity.java
package com.msh.organizer;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class SignUpActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new SignUpFragment())
.commit();
}
//Toast.makeText(this,"Sign Up", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SignUpFragment.java
package com.msh.organizer;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignUpFragment extends Fragment implements View.OnClickListener {
private Button mSignUpButton;
private EditText mNickNameEditText;
private EditText mEmailEditText;
private EditText mPasswordEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_up, container, false);
mSignUpButton = (Button) rootView.findViewById(R.id.sign_up_btn);
mNickNameEditText = (EditText) rootView.findViewById(R.id.nickname_et);
mEmailEditText = (EditText) rootView.findViewById(R.id.email_et);
mPasswordEditText = (EditText) rootView.findViewById(R.id.password_et);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSignUpButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_up_btn:
trySignUp();
break;
}
}
private void trySignUp() {
String nickname = mNickNameEditText.getText().toString();
String email = mEmailEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
boolean failed = false;
if (TextUtils.isEmpty(nickname)){
mNickNameEditText.setError("Nickname cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(password)){
mPasswordEditText.setError("Password cannnot be empty!");
failed = true;
}
if (TextUtils.isEmpty(email)){
mEmailEditText.setError("Email cannnot be empty!");
failed = true;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
mEmailEditText.setError("Inwalid E-mail address!");
failed = true;
}
if (!failed){
signUp(nickname, email, password);
}
}
private void signUp(String nickname, String email, String password) {
ParseUser user = new ParseUser();
user.setUsername(email);
user.setPassword(password);
user.setEmail(email);
// other fields can be set just like with ParseObject
user.put("nickname", nickname);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
if (getActivity() != null){
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
} else {
if (getActivity() != null) {
Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}

You can use Toolbar inside an AppBarLayout in your activity:
SignUpActivity.java
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
...
activity_sign_up.xml
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.msh.organizer.SignUpActivity"
tools:ignore="MergeRootFrame" />

Related

Android Studio Grid View doesn't show when I run the app

I created a Java class that should display something like this:
But this is what I get when I run the app:
It doesn't show what I wanted and Android Studio doesn't show any error in Logcat, so I don't know why it's not working.
This is the code for the class SetsActivity:
package com.example.myquiz;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toolbar;
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.set_toolbar);
//setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridview);
SetsAdapter adapter = new SetsAdapter(2);
sets_grid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{
SetsActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I also created an adapter class SetsAdapter so I'm gonna post the code for it as well:
package com.example.myquiz;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
} else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(),QuestionActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.setNo_tv)).setText(String.valueOf(position + 1));
return view;
}
}
And here is the code for the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".SetsActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/set_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
></androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sets"
android:textSize="26sp"
android:textStyle="bold"
android:padding="16dp" />
<GridView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/sets_gridview"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="16dp"
android:verticalSpacing="16dp"
android:padding="16dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
></GridView>
</LinearLayout>
Here is the code for the XML file set_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/round_corner"
android:backgroundTint="#FFC3C3"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/setNo_tv"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="45sp"></TextView>
</LinearLayout>
The getCount() method in the SetsAdapter should return numOfSets not 0.
#Override
public int getCount() {
return numOfSets;
}

Why item on menu drawer can't click ? Android Navigation

I have a really interesting problem with my Navigator menu. I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image. I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
image - this trouble
image - can't click
this my code :
menu_bar.java
package com.database.m.lyburan;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.database.m.lyburan.adapter.EventAdapter;
import com.database.m.lyburan.app.AppController;
import com.database.m.lyburan.data.EventData;
import com.database.m.lyburan.util.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.database.m.lyburan.Buddies.TAG_MESSAGE;
import static com.database.m.lyburan.Login.TAG_USERNAME;
import static com.database.m.lyburan.R.id.parent;
public class menu_bar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
FragmentManager fragmentManager;
Fragment fragment = null;
ListView list;
SharedPreferences sharedpreferences;
SwipeRefreshLayout swipe;
List<EventData> eventList = new ArrayList<EventData>();
private static final String TAG = menu_bar.class.getSimpleName();
private static String url_list = Server.URL + "event.php?offset=";
private int offSet = 0;
int no;
EventAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
private Boolean isFabOpen = false;
private FloatingActionButton fab, fab1, fab2;
private CardView card1, card2;
private Animation fab_open, fab_close, rotate_forward, rotate_backward, card_open, card_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
fragment = new Root();
callFragment(fragment);
}
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list_event);
eventList.clear();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(menu_bar.this, Buddies.class);
intent.putExtra(TAG_ID, eventList.get(position).getId());
startActivity(intent);
}
});
adapter = new EventAdapter(menu_bar.this, eventList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callEvent(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
Button meet_buddies = (Button) findViewById(R.id.meet_buddies);
meet_buddies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,Buddies.class);
startActivity(intent);
}
});
Button upcoming = (Button) findViewById(R.id.upcoming);
upcoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,asd.class);
startActivity(intent);
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
card1 = (CardView) findViewById(R.id.card1);
card2 = (CardView) findViewById(R.id.card2);
/*kenalkan animasi*/
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
card_open=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_open);
card_close=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_close);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animateFAB();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(menu_bar.this,Addhome.class);
startActivity(intent);
}
});
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menu_bar.this, "New Call", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bar, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_payment) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_help) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.btn_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_containers, fragment)
.commit();
}
public void animateFAB() {
/*jika fab dalam keadaan false*/
if (isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
card1.startAnimation(card_close);
card2.startAnimation(card_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
} else {
/*jika dalam keadaan true*/
fab.startAnimation(rotate_forward);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
card1.startAnimation(card_open);
card2.startAnimation(card_open);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
}
#Override
public void onRefresh() {
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
private void callEvent(int page){
swipe.setRefreshing(true);
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
EventData news = new EventData();
no = obj.getInt(TAG_NO);
news.setId(obj.getString(TAG_ID));
news.setJudul(obj.getString(TAG_JUDUL));
if (!Objects.equals(obj.getString(TAG_GAMBAR), "")) {
news.setGambar(obj.getString(TAG_GAMBAR));
}
news.setDatetime(obj.getString(TAG_TGL));
news.setIsi(obj.getString(TAG_ISI));
// adding news to news array
eventList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
activity_menu_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/meet_buddies"
android:layout_width="fill_parent"
android:drawableLeft="#drawable/ic_profil_w"
android:background="#color/ijo"
android:textColor="#android:color/background_light"
android:layout_height="wrap_content"
android:padding="15dp"
android:onClick="meet"
android:layout_marginTop="70dp"
android:text="Meet Buddies"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/upcoming"
android:layout_width="170dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Notification"
android:layout_marginTop="135dp" />
<Button
android:id="#+id/myshared"
android:layout_width="190dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="135dp"
android:text="My Shared"
/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:stateListAnimator="#null"
android:src="#drawable/ic_plus_w"
app:backgroundTint="#color/colorAccent"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="130dp"
android:stateListAnimator="#null"
android:layout_marginRight="#dimen/fab_margin"
android:visibility="invisible"
android:src="#drawable/ic_menu_camera"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="140dp"
android:layout_marginRight="75dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Event" />
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_beranda"
android:visibility="invisible"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="70dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Homestay" />
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="198dp" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_marginTop="222dp"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_event"
android:layout_width="wrap_content"
android:layout_height="330dp"
android:divider="#null"
android:dividerHeight="2dp"
android:layout_marginTop="222dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
i've tried, how can i fix it ? anyone please help me. thanks.
Anyone else having similar problem. It appears the order in the XML matters too.
I had my NavigationView and after it I had a layout included and I couldn't click an item on the NavigationView.
After I switched them, so that my layout was being included AND THEN AFTER IT I had my NavigationView, it worked ...
this adapter.java
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataModel> item;
public Adapter(Activity activity, List<DataModel> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_buddies, null);
TextView txt_nama = (TextView) convertView.findViewById(R.id.custom_list_item_text1);
txt_nama.setText(item.get(position).getNama());
return convertView;
}
}
You need to create this type of your layout xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
</android.support.v4.widget.DrawerLayout>
In FrameLayout you need to replace all fragment one by one like
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Note: You can write your Coordinator layout and other in fragment itself, may be helpful for you.

How to add the ListView element to be referenced in the individual Activity files

The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.

Viewpager in Dialog?

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>
Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.xml
<RelativeLayout 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"
android:background="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.
Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>

ParseUser search

I am trying to create a simple user search page for my app. I tried to create a ParseQuery and display results in a Listview in my main activity page. However, when I run program, I could not get a result of a search, program displays nothing. I will be happy if I get an answer.
Here is my MainActivity.java;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.results);
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.activity_main, R.layout.search_list );
//mainAdapter.setTextKey("username");
userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
uName = searchArea.getText().toString();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
mainAdapter.add((ParseUser)objects.get(i));
}
} else {
// Something went wrong.
e.printStackTrace();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my main activity xml file;
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp" >
</ListView>
</RelativeLayout>
I solved this problem. Here is updated version of code;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
//private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
private ArrayList<ParseUser> resultList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.userResultList);
resultList = new ArrayList<ParseUser>();
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.list_item, R.id.user_results,resultList);
//mainAdapter.setTextKey("username");
//userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String uName = searchArea.getText().toString();
final ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
resultList.add((ParseUser)objects.get(i));
}
userList.setAdapter(mainAdapter);
Toast.makeText(getApplicationContext(), "User is Found",
Toast.LENGTH_LONG).show();
} else {
// Something went wrong.
e.printStackTrace();
Toast.makeText(getApplicationContext(), "User is not Found",
Toast.LENGTH_LONG).show();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Moreover I need one more xml file to display the list. it is list_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="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/user_results"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
and main xml file, activity_main.xml;
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/userResultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/searchField"
android:layout_below="#+id/searchField"
android:layout_marginTop="39dp" >
</ListView>
</RelativeLayout>
put uName = searchArea.getText().toString(); inside the listener, you are setting uName only once when the view is created, so it will be empty. You need to get the text after the user enters input and the button is clicked.

Categories