App Crashes whenever I click an Icon on Navigation bar - android-studio

Just got many problems sorted out on my bottom navigation bar, but now the app crashes whenever I click on any of the 3 navigation bar Icons.
Error
2020-07-23 15:41:26.397 25876-25876/com.example.sociate11 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sociate11, PID: 25876
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:343)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:293)
at com.example.sociate11.activityHome$2.onNavigationItemSelected(activityHome.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
activityHome.java
package com.example.sociate11;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class activityHome extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogOut);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(activityHome.this, MainActivity.class));
}
});
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_fragment:
selectedFragment = new HomeFragment();
break;
case R.id.events_fragment:
selectedFragment = new EventFragment();
break;
case R.id.fragment_myconversation:
selectedFragment = new ConversationFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
ConversationsFragment.java (all 3 fragments are currently identical)
package com.example.sociate11;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_myconversations,container,false);
}
}
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="Home"
android:icon="#drawable/ic_home"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myEvents"
android:title="My Events"
android:icon="#drawable/ic_event"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myConversations"
android:title="My Conversations"
android:icon="#drawable/ic_conversations"
app:showAsAction="always"/>
</menu>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".activityHome"
android:background="#color/colorPrimary">
<Button
android:id="#+id/btnLogOut"
android:layout_width="115dp"
android:layout_height="75dp"
android:text="log out"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_bar" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#color/colorPrimaryDark"
app:itemIconTint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogOut"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you for the help as always, and please let me know if I didn't provide enough info!

Related

Android Studio Recycler View have gaps between the rows. Help me fix

I followed this tutorial on youtube for my school project. The app is able to display selected images from gallery but the recycler view have gaps in every row. What do I code to fix this app? help. enter image description here
here's my 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/pick"
android:layout_width="53dp"
android:layout_height="64dp"
android:layout_margin="12dp"
android:layout_weight="0"
android:backgroundTint="#FF5722"
android:text="+"
android:textSize="24sp"
app:cornerRadius="64dp" />
<TextView
android:id="#+id/totalPhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:textColor="#FFFFFF" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_Gallery_Images"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
</LinearLayout>
RecyclerAdapter.java
package com.example.mygram;
import android.media.Image;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Uri> uriArrayList;
public RecyclerAdapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_single_image,parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(uriArrayList.get(position));
}
#Override
public int getItemCount() {
return uriArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
Custom single images.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here's the MainActivity.java
package com.example.mygram;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView;
Button pick;
ArrayList <Uri> uri = new ArrayList<>();
RecyclerAdapter adapter ;
private static final int Read_Permission = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.totalPhotos);
recyclerView = findViewById(R.id.recyclerView_Gallery_Images);
pick = findViewById(R.id.pick);
adapter = new RecyclerAdapter(uri);
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
recyclerView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
}
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
if(data.getClipData() !=null) {
int x = data.getClipData().getItemCount();
for (int i = 0; i < x; i++) {
uri.add(data.getClipData().getItemAt(i).getUri());
}
adapter.notifyDataSetChanged();
textView.setText("Photos ("+uri.size()+")");
}else if (data.getData()!=null){
String imageURL=data.getData().getPath();
uri.add(Uri.parse(imageURL));
}
}
}
}
The concept of the app is instagram feed tester. I want to be able to display images like the grid in instagram but the gap is appearing preventing it to happen. help me please thankyou
In your Custom single images.xml replace the height of the parent layout to wrap_content. Replace your code with the following
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Everything is right : Just need to Change this to this: (images.xml)
android:layout_height="match_parent"
to
android:layout_height="wrap_content"
in your model xml file

Youtube Player View not displaying video using with youtube API and channel import

I am using youtube API top import youtube channel in android app. I have created MainActivity, Adapter, Video Datails Class and another activity named youtubePlay activity. the xml for main activity consists of list view and another custom layout with text and image for list view items display obtained from json parsing (title, description, thumbnail). I have added youtube player view in the activity_play_youtube. but on clicking the video from list, the video is not displayed on the youtube player view.
the coding is as shown;
MainActivity.java
package com.currentmedia.channel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.currentmedia.channel.Adapter.MyCustomAdapter;
import com.currentmedia.channel.Model.VideoDetails;
import static android.widget.Toast.*;
public class MainActivity extends AppCompatActivity {
//private static final String TAG = "Channel Activity";
String API_Key = "[]";
ListView listView;
ArrayList<VideoDetails> videoDetailsArrayList;
MyCustomAdapter myCustomAdapter;
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&key=[]";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
videoDetailsArrayList = new ArrayList<>();
myCustomAdapter = new MyCustomAdapter(MainActivity.this, videoDetailsArrayList);
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsArrayList.add(vd);
}
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(), LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
}
the adapter class named myCustomAdapter is following
package com.currentmedia.channel.Adapter;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.currentmedia.channel.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import com.currentmedia.channel.Model.VideoDetails;
public class MyCustomAdapter extends BaseAdapter {
Activity activity;
ArrayList<VideoDetails> videoDetailsArrayList;
LayoutInflater inflater;
public MyCustomAdapter(Activity activity, ArrayList<VideoDetails> videoDetailsArrayList)
{
this.activity=activity;
this.videoDetailsArrayList=videoDetailsArrayList;
}
#Override
public Object getItem(int position) {
return this.videoDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater==null)
{inflater=this.activity.getLayoutInflater();}
if(convertView == null)
{convertView=inflater.inflate(R.layout.custom_layout,null);}
ImageView imageView=(ImageView) convertView.findViewById(R.id.imageView);
TextView textView=(TextView) convertView.findViewById(R.id.mytitle);
LinearLayout linearLayout=(LinearLayout)convertView.findViewById(R.id.root);
final VideoDetails videoDetails=(VideoDetails) this.videoDetailsArrayList.get(position);
linearLayout.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(activity, com.currentmedia.channel.VideoPlayActivity.class);
i.putExtra("videoId", videoDetails.getVideoId());
activity.startActivity(i);}
});
Picasso.get().load(videoDetails.getUrl()).into(imageView);
textView.setText(videoDetails.getTitle());
return convertView;
}
#Override
public int getCount() {
return this.videoDetailsArrayList.size();
}
}
videoPlayActivity.java
package com.currentmedia.channel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubePlayerView;
public class VideoPlayActivity extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_play);
youTubePlayerView= (YouTubePlayerView) findViewById(R.id.youtube_player) ;
}
}
and the xml files are :
activity_video_play
<?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"
tools:context=".VideoPlayActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/youtube_player"></com.google.android.youtube.player.YouTubePlayerView>
</RelativeLayout>
while activity_main and custom_layout is as follows
<?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"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"></ListView>
</RelativeLayout>
<?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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:id="#+id/root">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:id="#+id/mytitle"
android:text="welcome to my video"
android:textSize="16sp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
can anybody explain where am I doing wrong?
In your videoPlayActivity.java
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
String url = getIntent().getStringExtra("videoId");
youTubePlayerView = findViewById(R.id.youtube_player);
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(url);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
youTubePlayerView.initialize("Api key", onInitializedListener);
To generate Api key https://developers.google.com/youtube/android/player/register

Adding language settings button to an app?

I want to add a spinner to my app to change the language of strings in an array list but not sure how to do so.
I made a sample app to try to change and tried couple of things but they didn't work. I know it's a basic thing but I really have no idea how to do it.
Here is the code for XML layout file
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<Spinner
android:id="#+id/language_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/list_item"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/list_item"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/list_item"
android:layout_width="368dp"
android:layout_height="352dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
For the main activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner languageSpinner = (Spinner) findViewById(R.id.language_spinner);
final ListView list = (ListView) findViewById(R.id.list_item);
/*Creating an ArrayAdapter that is populated with languagelist to populate the languageSpinner*/
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.language_list, android.R.layout.simple_dropdown_item_1line);
/*Populating the languageSpinner with the spinnerAdapter*/
languageSpinner.setAdapter(spinnerAdapter);
languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
Toast.makeText(getApplicationContext(), "Language changed to " + (CharSequence) languageSpinner.getSelectedItem() , Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(getApplicationContext(), "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this ,android.R.layout.simple_list_item_1, arrayList ) ;
list.setAdapter(arrayAdapter);
}
}
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
configuration.setLocale(Locale.forLanguageTag("fa"));
resources.updateConfiguration(configuration, displayMetrics);
finish();
startActivity(getIntent());
First of all you have to build a new string file in a new values folder in your resource folder for example i want to add persian in my app and build a value file with the name of values-fa and copy your string.xml file to it
and change the string to the language you want .
and then you have to add this code to your spinner OnItemSelectedListener(). This work for me.

Trying to add scrollable tabs in a fragment that extends FragmentActivity, but unable to find the mistake

MyEventsFragment.java
List item
package com.example.edvenswa.collabevents;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class MyEventsFragment extends FragmentActivity{
ViewPager viewPager = null;
MyAdapter myAdapter;
public MyEventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_my_events);
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
/*List<Fragment> listFragments = new ArrayList<Fragment>();
listFragments.add(new MyEventsInsideFragment());
listFragments.add(new ExpiredEventsFragment());
listFragments.add(new AttendingEventsFragment());
listFragments.add(new PastAttendingEventsFragment());*/
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
viewPager.setAdapter(myAdapter);
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my_events, container, false);
}*/
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Log.d("count","count called"+i);
Fragment fragment = null;
if (i == 0) {
fragment = new MyEventsInsideFragment();
}
if (i == 1) {
fragment = new ExpiredEventsFragment();
}
if (i == 2) {
fragment = new AttendingEventsFragment();
}
if (i == 3) {
fragment = new PastAttendingEventsFragment();
}
return fragment;
}
#Override
public int getCount() {
Log.d("count", "count called");
return 4;
}
}
fragment_my_events.xml
<FrameLayout 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="com.example.edvenswa.collabevents.MyEvents">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/myEventsPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:gravity="center">
</android.support.v4.view.ViewPager>
</FrameLayout>
So, this is my code. here I am able to view the first page in fragment but unable scroll and no view of other fragments.
Note: This MyEventsFragment.java is also a fragment in the sidedrawer.
First add the design support library if you haven't
compile 'com.android.support:design:23.0.0'
then add the TabLayout like this one.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
Then in your onCreate() method below the viewPager add the following line,
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
Also, in your FragmentPageAdapter, you'll have to override getPageTitle() method for returning your Tabs title.

App Crash: FATAL EXCEPTION: main

App Crash on button click. Here is the log.
Dealing specifically with trying to store a user into Parse.com as my backend. I have a java class called RegisterActivity with corresponding xml file, leading me to think it could be a null pointer exception, but I tested, and that doesnt seem to be the problem. Here are the 3 classes in which I believe are involved with the problem.
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
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 RegisterActivity extends Activity {
protected EditText mUsername;
protected EditText mUserEmail;
protected EditText mUserPassword;
protected Button mRegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//initialize
mUsername = (EditText)findViewById(R.id.usernameRegisterEditText);
mUserEmail= (EditText)findViewById(R.id.emailRegisterEditText);
mUserPassword= (EditText)findViewById(R.id.passwordRegisterEditText);
mRegisterButton = (Button)findViewById(registerButton);
//listen to register button click
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the username,password, and email, then convert to string
String username = mUsername.getText().toString().trim();
String email = mUserEmail.getText().toString().trim();
String password = mUserPassword.getText().toString().trim();
//store user and parse
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(email);
user.setEmail(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e == null){
//user signed up successfully
Toast.makeText(RegisterActivity.this, "Welcome!", Toast.LENGTH_LONG).show();
//take user to homepage
}else{
//error signing up user
}
}
});
}
});
}
#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_register, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the corresponding activity_register.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.parse.inclassmode.RegisterActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="username"
android:ems="10"
android:id="#+id/usernameRegisterEditText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="142dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="email"
android:ems="10"
android:id="#+id/emailRegisterEditText"
android:layout_below="#+id/usernameRegisterEditText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="password"
android:ems="10"
android:id="#+id/passwordRegisterEditText"
android:layout_below="#+id/emailRegisterEditText"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sign up"
android:id="#+id/registerButton"
android:layout_marginTop="42dp"
android:layout_below="#+id/passwordRegisterEditText"
android:layout_alignParentStart="true" />
</RelativeLayout>
MainActivity.java class which includes my keys for Parse.com
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.Parse;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Enable Local Datastore, ID's hidden
Parse.initialize(this, "id", "id");
}
#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_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and finally my android manifest, which launches the register activity then takes the user to the home screen.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.inclassmode" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".RegisterActivity"
android:label="#string/title_activity_register" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="InClassMode" >
</activity>
</application>
</manifest>
Figured it out!
For those of you who may come across this problem, create a new class that is not an activity, from there, initialize the Parse.

Resources