Dynamically created Views don't appear in the GridLayout properly - java

I have a GridLayout in which I want dynamically generated TextViews to be displayed. At least the GridLayout can have 2 columns and at most it can have 3 columns.
I have a function called decide(int) that passes an integer argument to another function that actually generates the TextViews dynamically. This integer value is then tested to decide the number of columns and rows the GridLayout can have.
Following is my MainActivity.java
package accordiontry.juspay.accordiontry;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private GridLayout gridLayout;
private final int FixedCol3 = 3, FixedCol2 = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
init();
handleClick();
decide(6);
}
#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);
}
private void init()
{
gridLayout = (GridLayout) findViewById(R.id.gridLayout);
}
public void handleClick()
{
}
private void decide(int num)
{
if((num%3)==0 || (num%2)==0)
generateView(num);
else
{
num = num -1;
generateView(num);
}
}
public void generateView(int num)
{
if(((num%3)==0 && (num%2)==0) || (num%3)==0)
{
Toast.makeText(MainActivity.this,"3 has been executed", Toast.LENGTH_SHORT).show();
int number = num/3;
if(number>1)
{
gridLayout.setRowCount(number);
gridLayout.setColumnCount(FixedCol3);
createView(number*FixedCol3);
}
else
{
gridLayout.setRowCount(1);
gridLayout.setColumnCount(FixedCol3);
createView(number*FixedCol3);
}
}
else
{
Toast.makeText(MainActivity.this,"2 has been executed", Toast.LENGTH_SHORT).show();
int number = num/2;
if(number>1)
{
gridLayout.setRowCount(number);
gridLayout.setColumnCount(FixedCol2);
createView(number*FixedCol2);
}
else
{
gridLayout.setRowCount(1);
gridLayout.setColumnCount(FixedCol2);
createView(number*FixedCol2);
}
}
}
public void createView(int n)
{
for(int i=0;i<n;i++)
{
TextView tv = new TextView(this);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = GridLayout.LayoutParams.MATCH_PARENT;
tv.setLayoutParams(params);
tv.setText("HEY THERE!!!");
gridLayout.addView(tv);
}
}
}
And following is my content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="accordiontry.juspay.accordiontry.MainActivity"
tools:showIn="#layout/activity_main">
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="129dp">
</GridLayout>
</RelativeLayout>
This is the output I'm getting: -
My app is supposed to generate 6 Hey There!! TextViews, but instead it ends up generating just 2.
Where am I going wrong?
Thank you for your time!!

Make your gridlayout's height to wrap_content.
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="129dp">
</GridLayout>

Found the solution myself.
Changing
params.width = GridLayout.LayoutParams.MATCH_PARENT;
to
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
did the trick.

Related

Programmatically loading parse images and text into linear layout

I am trying to create a list of items followed by their name and caloric value in a similar way to the image below.
However I am trying to do this while getting all my data from Parse. I have got it down for the most part but I have been stuck for hours trying to programatically add these two text views and image one after the other (text then view) as I loop through them.
I have been skeptical to make major changes to the code as I am not very proficient with android, however from what I have looked at so far my case seems to be unique in the sense that it involves both Parse and using textviews and imageviews together.
Below is what I've got so far on this activity:
XML
<?xml version="1.0" encoding="utf-8"?>
<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=".AdminProductsListActivity">
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/linLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Class
package com.parse.starter;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class AdminProductsListActivity extends AppCompatActivity {
LinearLayout linLayout;
Intent intent;
String name;
TextView itemName;
TextView itemCalories;
ImageView imageView;
public void showMain() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void addNewProduct() {
Intent intent = new Intent(getApplicationContext(), AddNewProductActivity.class);
intent.putExtra("shop", name);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.new_admin_settings_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.newItem){
ParseUser.logOut();
addNewProduct();
} else if (item.getItemId() == R.id.logout){
ParseUser.logOut();
showMain();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_products_list);
intent = getIntent();
name = intent.getStringExtra("username");
linLayout = (LinearLayout) findViewById(R.id.linLayout);
setTitle(name);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Product");
query.whereEqualTo("username", name);
query.orderByDescending("objectID");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null && list.size() > 0){
for (ParseObject object : list){
ParseFile file = (ParseFile) object.get("image");
//if (itemName != null && itemCalories != null){
itemName = new TextView(getApplicationContext());
itemName.setText(object.getString("name"));
itemName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
itemCalories = new TextView(getApplicationContext());
itemCalories.setText(object.getString("calories") + " kcal");
itemCalories.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
linLayout.addView(itemCalories);
linLayout.addView(itemName);
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null && bytes != null){
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
imageView.setImageBitmap(bitmap);
linLayout.addView(imageView);
}
}
});
}
}
}
});
}
}
Right now what happens is all the text goes to the top and images goes to the bottom. I've also tried doing this:
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null && bytes != null){
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
imageView.setImageBitmap(bitmap);
linLayout.addView(imageView);
linLayout.addView(itemCalories);
linLayout.addView(itemName);
But then I get this Error:
The specified child already has a parent. You must call removeView() on the child's parent first.
and none of the answers to this error that I found seem to be helpful in this situation.
Long story short, I'm not even looking for something super complex or for it to look good, I am just a beginner. I just want to load the textviews and then the imageview one after the other, just like in the image, while using parse.
Any ideas?

Android Studio app crashes when i try to test it

The app crashes when i tried to test, i am using fragments to create the app:
App crashed
I have this in audioFragment.java:
package amaguenet.com.reproductorxassidas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class audioFragment extends Fragment {
// variable declaration
private ListView mainList;
private MediaPlayer mp;
private final String[] listContent = {"Ahonzubilahi Min Mayli", "Ajabani Khayru Baqin", "Ajabani Rabbu Sama", "Ala Innani Usni",
"Alal Muntaqa Khayril Baraya"};
private final int[] resID = {R.raw.ahonzu_bilahi_min_mayli, R.raw.ajabani_khayru_baqin, R.raw.ajabani_rabbu_sama,
R.raw.ala_innani_usni, R.raw.alal_muntaqa_khayril_baraya};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_audio, container, false);
// Initializing variables
mp = new MediaPlayer();
mainList = (ListView) v.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listContent);
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
playSong(position);
}
});
return v;
}
public void playSong(int songIndex) {
// Play song
mp.reset();// stops any current playing song
mp = MediaPlayer.create(getActivity().getApplicationContext(), resID[songIndex]);// create's
// new
// mediaplayer
// with
// song.
mp.start(); // starting mediaplayer
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
}
#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);
}
public interface OnFragmentInteractionListener {
}
}
And this in a in fragment_audio (the layout):
<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"
tools:context="amaguenet.com.reproductorxassidas.audioFragment"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
Can some helps with this, i am using Fragments in Android Studio?
You can use getIdentifier() method, here is a simple example:
private final int resID = getContext().getResources().getIdentifier(direction, "raw", PACKAGE_NAME);
direction - string with your file name f.e: "ahonzu_bilahi_min_mayli"
PACKAGE_NAME - is your package name

my UI isn't working (buttons)

I have an app and all of a sudden my user interface stopped working the share button works and also the options menu but for some odd reason my buttons stopped working they don't click or do anything . is it due to possibly the extending of my OptionsMenu class ? I have no idea why ? Does this happen often I tries to freshly build my project but no use . I have my MainActivity Class here
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.AdapterView;
import android.widget.TextView;
import java.io.*;
import android.content.*;
import android.view.*;
import android.media.*;
import javax.security.auth.*;
import android.util.*;
import android.widget.AdapterView.*;
import java.net.*;
import org.apache.http.util.*;
import android.webkit.*;
import java.text.*;
import android.graphics.*;
import android.widget.TextView.*;
import android.text.*;
import android.widget.ActionMenuView.*;
import android.view.MenuItem.*;
import android.widget.*;
import android.content.Intent;
import android.net.*;
import java.util.*;
import java.nio.channels.*;
import java.nio.*;
import android.*;
public class MainActivity extends OptionsMenu
{
private MusicPlayer musicPlayer;
private String pos = "";
private FileManager fm;
private BlueTheme BlueTheme;
private PinkTheme PinkTheme;
private Downloader downloader;
private EditTextCustomizable etc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
musicPlayer = new MusicPlayer(new MediaPlayer());
fm = new FileManager(this,this);
BlueTheme = new BlueTheme(this,this ,fm);
PinkTheme = new PinkTheme(this,this,fm);
etc = new EditTextCustomizable(this , BlueTheme , PinkTheme);
etc.customize();
Button rewind = (Button)findViewById(R.id.rewind);
rewind.setText("<");
Button fwd = (Button)findViewById(R.id.fwd);
fwd.setText(">");
ListView downloadsList = (ListView) findViewById(R.id.downloads);
downloadsList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3){
ListView downloadsList = (ListView) findViewById(R.id.downloads);
pos = downloadsList.getItemAtPosition(position).toString();
musicPlayer.InitPlay(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/" + pos);
}});
}
public void Play(View view){
musicPlayer.Play();
EditText search = (EditText)findViewById(R.id.search);
musicPlayer.SearchResult(search.getText().toString());
}
public void Pause(View view){
musicPlayer.Pause();
}
public void Stop(View view){
musicPlayer.Stop();
}
public void Rewind(View view){
musicPlayer.Rewind();
}
public void Fwd(View view){
musicPlayer.Fwd();
}
public void onDownloadClick(View view){
EditText bar = (EditText)findViewById(R.id.search);
String downloadFile = bar.getText().toString();
downloader.DownloadURL(downloadFile);
}
}
And here is the OptionsMenu class where I am extending Activity note that I am not using AppCompatActivity .
package com.mycompany.myapp;
import android.view.*;
import android.app.*;
import android.net.*;
import java.util.*;
import android.widget.ListView;
import android.content.*;
import java.io.*;
import android.widget.*;
import android.*;
public class OptionsMenu extends Activity
{
private MusicPlayer musicPlayer;
private FileManager fm;
private BlueTheme blueTheme;
private PinkTheme pinkTheme;
private final int blue = Menu.FIRST;
private final int pink = blue + 1;
private int items = 0;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
fm = new FileManager(this,this);
blueTheme = new BlueTheme(this,this,fm);
pinkTheme = new PinkTheme(this,this,fm);
fm.ListFiles();
menu.clear();
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.sidebar_menu, menu);
SubMenu subMenu = menu.addSubMenu("Themes");
subMenu.add(0 , blue , 0 , "Blue");
subMenu.add(0, pink , 1, "Pink");
items = subMenu.getItem().getItemId();
// tool bar menu
ArrayList<Uri> al = new ArrayList<Uri>();
ArrayList<Uri> emailAl = new ArrayList<Uri>();
MenuItem mi = menu.findItem(R.id.searchable);
MenuItem share = menu.findItem(R.id.share);
mi.setIcon(android.R.drawable.ic_search_category_default);
SearchView searchView = (SearchView) menu.findItem(R.id.searchable).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
ShareActionProvider sap = (ShareActionProvider) share.getActionProvider();
Intent intentShare = new Intent(Intent.ACTION_SEND_MULTIPLE);
Intent intentEmail = new Intent(Intent.ACTION_SEND_MULTIPLE);
intentShare.setType("audio/mp3");
intentEmail.setType("audio/mp3");
Uri uri = null;
Uri uriEmail = null;
//FileInputStream in = null;
//FileOutputStream out = null;
//try{
// for(File file : downloads){
// uri = Uri.fromFile(file);
// in = new FileInputStream(file);
// File outFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), file.getName()); // IMPORTANT! You need to create your file object separately, so you can then pass it to intent as well..
// out = new FileOutputStream(outFile);
// byte[] buf = new byte[1024];
// int len;
// while ( (len = in.read(buf, 0, buf.length)) != -1){
// out.write(buf, 0, len);
// }
// in.close();
// out.flush();
// out.close();
// uriEmail = Uri.fromFile(outFile); // Here you passed the parent directory file.. Pass newly created file object ..
// al.add(uri);
// emailAl.add(uriEmail);
// }
// } catch(IOException e){
// e.printStackTrace();
// }
//for(File file : fm.GetDownloadFiles()){
// uriEmail = Uri.fromFile(fm.exportFile(file));
//}
emailAl.add(uriEmail);
intentShare.putParcelableArrayListExtra(Intent.EXTRA_STREAM,al );
intentEmail.putParcelableArrayListExtra(Intent.EXTRA_STREAM,emailAl);
intentEmail.putExtra(Intent.EXTRA_SUBJECT , "Subject");
intentEmail.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sap.setShareIntent(intentShare);
sap.setShareIntent(intentEmail);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId()){
case R.id.playlist:
break;
case blue:
blueTheme.Blue();
break;
case pink:
pinkTheme.Pink();
break;
case R.id.muteoption:
musicPlayer.MuteVolume();
break;
case R.id.unmuteoption:
musicPlayer.UnMuteVolume();
break;
default:
return super.onOptionsItemSelected(item);
// TODO: Implement this method
}
return super.onOptionsItemSelected(item);
}
}
I can post up more code if requested. And will reedit if not clear enough thank you
EDITED
Here is the layout XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="4dp"
android:showAsAction="always"
android:windowActionBar="false"
android:theme="#android:style/Theme.Holo.Light"
/>
<TextView
android:id="#+id/downloadsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/downloadButton"
android:text="#string/downloadButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:onClick="onDownloadClick"
/>
<EditText
android:id="#+id/search"
android:hint="Do something"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="#id/downloadButton"
android:background="#android:color/transparent"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
<Button
android:id="#+id/pause"
android:text="#string/pause"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Pause"
android:layout_centerInParent="true"
android:layout_below="#id/search"
/>
<Button
android:id="#+id/play"
android:text="#string/play"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Play"
android:layout_toRightOf="#id/pause"
android:layout_below="#id/search"/>
<Button
android:id="#+id/stop"
android:text="#string/stop"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="Stop"
android:layout_toLeftOf="#id/pause"
android:layout_below="#id/search"/>
<Button
android:id="#+id/rewind"
android:text="#string/rewind"
android:layout_height="wrap_content"
android:layout_width="50dp"
android:onClick="Rewind"
android:layout_toLeftOf="#id/stop"
android:layout_below="#id/search"/>
<Button
android:id="#+id/fwd"
android:text="#string/fwd"
android:layout_height="wrap_content"
android:layout_width="50dp"
android:onClick="Fwd"
android:layout_toRightOf="#id/play"
android:layout_below="#id/search"/>
<ListView
android:id="#+id/downloads"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rewind"
/>
</RelativeLayout>
Paste your layout xml if possible. I guess it's caused by something (maybe some parent view) interrupted the focus, so the child view button can't get focus.

Trouble getting video to play on Recyclerview

I have a VideoView inside a RecyclerView. I want to eventually have a list of videos to play on a Recyclerview. I decided to start out with one video, then move on to having multiple videos. I can't seem to get one video to play in the Recyclerview. When I start the app on my phone, all I get is the progress bar. The onPrepared function is never called for some reason. Here's my code.
RecyclerActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.RecyclerView;
public class RecyclerActivity extends ActionBarActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(this);
mRecyclerView.setAdapter(mAdapter);
}
#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_recycler, 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);
}
}
MyAdapter.java
import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private ProgressDialog progressDialog;
private MediaController mediaControls;
public static class ViewHolder extends RecyclerView.ViewHolder{
public VideoView mVideoView;
public ViewHolder(View v){
super(v);
mVideoView = (VideoView) v.findViewById(R.id.video_view);
}
}
public MyAdapter(Context mContext) {
context = mContext;
mediaControls = new MediaController(context);
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Random Video");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_video_view, parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
try{
holder.mVideoView.setMediaController(mediaControls);
holder.mVideoView.setVideoURI(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.kitkat));
} catch (Exception e){
Log.e("Error", e.getMessage());
e.printStackTrace();
}
holder.mVideoView.requestFocus();
holder.mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
holder.mVideoView.start();
}
});
}
#Override
public int getItemCount() {
return 1;
}
my_video_view.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
tools:context=".RecyclerActivity">
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
activity_recycler.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=".RecyclerActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Any ideas? The video file is a .3gp file by the way. Thanks!
I was stuck on this for far too long as well. After searching everywhere and still struggling I looked at my older code base with the exact same code bar one difference. The VideoView was having its height programatically set. android:layout_height="wrap_content" doesn't appear to make a height adjustment.
So I used a self made utility method to get the screen width and set the height to be in a 16:9 ratio like so. (Maybe just set your height and width to some arbitrary numbers first to see if it's the issue)
public static int getScreenWidth(Context c) {
int screenWidth = 0; // this is part of the class not the method
if (screenWidth == 0) {
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}
return screenWidth;
}
Then all it takes is to set the VideoViews height as such
holder.mVideoView.getLayoutParams().height = getScreenWidth(mContext) * 9 /16;
NOTE: My width is set to match_parent, so wrap_content may also fail there too.
Hope this helps.
the problem is with
android:layout_width="wrap_content"
android:layout_height="wrap_content"
before the video is loaded their values are 0 to solve this problem can use set minHeight to 1dp and layout_width to match_parent
and this will do the trick, you do not need fixed width and height.

Sendind data from one activity to another

Hi i'm new here and firstly i want to apologise for my language .I wanted to create my first android app ,and im curently struggle with some issues.
MainActivity ,which represents my main screen containing two buttons and spinner.In spinner user can choose one text file and after selection spinnerActivity should be triggered(screen with opened text file).I found problem because not every record from spinner trigger activity with text file that i want (one trigger file that i want and other trigger screen with empty TextView). Here is layout of spinnerActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView2"
android:layout_width="199dp"
android:layout_height="89dp"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="nie dziala" />
<TextView
android:id="#+id/proximityTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Code of MainACtivity
package com.example.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button click=(Button)findViewById(R.id.button2);
click.setOnClickListener(new View.OnClickListener(){ //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,AboutActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
final Button click2=(Button)findViewById(R.id.button1);
click2.setOnClickListener(new View.OnClickListener() { //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,RandomActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.recipie_array, android.R.layout.simple_spinner_item);
// Specify the layut to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// String i=Integer.toString(pos);
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
intent3.putExtra("txt",(pos));
startActivity(intent3);
}
if(pos==2)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
}
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#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 the code of spinneractivity
package com.example.myapp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class SpinnerActivity extends ActionBarActivity implements SensorEventListener {
TextView proxText;
SensorManager sm;
Sensor proxSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
//proximitymeter
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText=(TextView)findViewById(R.id.proximityTextView);
sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);
Intent intent3 = getIntent();
int value = intent3.getIntExtra("txt", 0);
//finish();
if (value==1)
{
open("przepis1.txt");
}
if (value==2)
{
open("przepis2.txt");
}
if (value==3)
{
open("przepis3.txt");
}
}
public void open(String name){
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,name);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader bufor = new BufferedReader(new FileReader(file));
String line;
while ((line = bufor.readLine()) != null) {
text.append(line);
text.append('\n');
}
bufor.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.textView2);
//Set the text
tv.setText(text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.spinner, 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);
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
//proxText.setText(String.valueOf(event.values[0]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Can someone look at this and help me with finding bugs?Thanks
Position starts form 0, I think problem is with the conditions,
You can write like this-
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Intent intent = new Intent(MainActivity.this, SpinnerActivity.class);
intent.putExtra("txt", pos + 1);
startActivity(intent);
}

Categories