CoordinatorLayout cannot be cast to android.support.v4.widget.DrawerLayout - android-activity

The app initialized with a splash and that shows and works well.
Then when you try to access the menu bar the app crashes.
This is my Main_Activity.j
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
/*
DECLARACIONES
*/
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private CharSequence activityTitle;
private CharSequence itemTitle;
private String[] tagTitles;
public class MainActivity extends AppCompatActivity {
/*
DECLARACIONES
*/
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private CharSequence activityTitle;
private CharSequence itemTitle;
private String[] tagTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
itemTitle = activityTitle = getTitle();
tagTitles = getResources().getStringArray(R.array.Tags);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
// Setear una sombra sobre el contenido principal cuando el drawer se despliegue
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//Crear elementos de la lista
ArrayList<DrawerItem> items = new ArrayList<DrawerItem>();
items.add(new DrawerItem(tagTitles[0], R.drawable.ic_html));
items.add(new DrawerItem(tagTitles[1], R.drawable.ic_css));
items.add(new DrawerItem(tagTitles[2], R.drawable.ic_javascript));
items.add(new DrawerItem(tagTitles[3], R.drawable.ic_angular));
items.add(new DrawerItem(tagTitles[4], R.drawable.ic_python));
items.add(new DrawerItem(tagTitles[5], R.drawable.ic_ruby));
// Relacionar el adaptador y la escucha de la lista del drawer
drawerList.setAdapter(new DrawerListAdapter(this, items));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
// Habilitar el icono de la app por si hay algún estilo que lo deshabilitó
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Crear ActionBarDrawerToggle para la apertura y cierre
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(itemTitle);
/*Usa este método si vas a modificar la action bar
con cada fragmento
*/
//invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(activityTitle);
/*Usa este método si vas a modificar la action bar
con cada fragmento
*/
//invalidateOptionsMenu();
}
};
//Seteamos la escucha
drawerLayout.setDrawerListener(drawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
// Toma los eventos de selección del toggle aquí
return true;
}
return super.onOptionsItemSelected(item);
}
/* La escucha del ListView en el Drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
drawerLayout.closeDrawer(drawerList);
}
}
private void selectItem(int position) {
// Reemplazar el contenido del layout principal por un fragmento
ArticleFragment fragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_ARTICLES_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// Se actualiza el item seleccionado y el título, después de cerrar el drawer
drawerList.setItemChecked(position, true);
setTitle(tagTitles[position]);
drawerLayout.closeDrawer(drawerList);
}
/* Método auxiliar para setear el titulo de la action bar */
#Override
public void setTitle(CharSequence title) {
itemTitle = title;
getSupportActionBar().setTitle(itemTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sincronizar el estado del drawer
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Cambiar las configuraciones del drawer si hubo modificaciones
drawerToggle.onConfigurationChanged(newConfig);
}
}
This is my content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</RelativeLayout>
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/drawer_layout"
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:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<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:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
errors
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: FATAL EXCEPTION: main`enter code here
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: Process: com.example.german.pedorreta, PID: 22911
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.german.pedorreta/com.example.german.pedorreta.MainActivity}: java.lang.ClassCastException:
android.support.design.widget.CoordinatorLayout cannot be cast to
android.support.v4.widget.DrawerLayout
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta
E/AndroidRuntime:
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread.access$800(ActivityThread.java:139)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Handler.dispatchMessage(Handler.java:102)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Looper.loop(Looper.java:136)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.main(ActivityThread.java:5086)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at dalvik.system.NativeStart.main(Native Method)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:Caused by: java.lang.ClassCastException: android.support.design.widget.CoordinatorLayout cannot be cast to android.support.v4.widget.DrawerLayout
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.example.german.pedorreta.MainActivity.onCreate(MainActivity.java:44)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.Activity.performCreate(Activity.java:5248)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.access$800(ActivityThread.java:139) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Handler.dispatchMessage(Handler.java:102) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Looper.loop(Looper.java:136) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.main(ActivityThread.java:5086) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at java.lang.reflect.Method.invokeNative(Native Method) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at java.lang.reflect.Method.invoke(Method.java:515) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)

You are missing a DrawerLayout in your activity_main.xml
Try wrapping the CoordinatorLayout with a DrawerLayout
<?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.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/main_menu"/>
</android.support.v4.widget.DrawerLayout>

Related

JavaFX Date Picker specific format error

I've created a Sample Application which uses JavaFX-8 Date Picker. It works fine on default pattern but on a specific pattern it throws a exception. I'm trying to convert it on 'DD-MM-YYYY' pattern on default.
Here is the Source File of the Program
Please take a look.
DatePickerController.java
package javafx.datepicker;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextArea;
import javafx.util.StringConverter;
public class DatePickerController {
#FXML
private DatePicker dp;
#FXML
private Button btn;
#FXML
private TextArea ta;
public void initialize() {
String pattern = "DD-MM-YYYY";
dp.setPromptText(pattern);
try {
dp.setConverter(new StringConverter<LocalDate>() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
#Override
public String toString(LocalDate object) {
if (object == null) {
return null;
}
return dtf.format(object);
}
#Override
public LocalDate fromString(String string) {
if (string != null & !string.isEmpty()) {
return LocalDate.parse(string, dtf);
}
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is Main Class
JavaFXDatePicker.java
package javafx.datepicker;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXDatePicker extends Application {
public static void main(String... args) {
launch(args);
}
#Override
public void start(Stage st) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/javafx/datepicker/DatePicker.fxml"));
Scene sc = new Scene(root);
st.setScene(sc);
st.setTitle("JavaFX Date Picker");
st.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And Here is FXML File
DatePicker.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="247.0" prefWidth="372.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="javafx.datepicker.DatePickerController">
<children>
<DatePicker fx:id="dp" layoutX="50.0" layoutY="51.0" prefHeight="25.0" prefWidth="273.0" />
<Button fx:id="btn" layoutX="50.0" layoutY="99.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="273.0" text="Click" />
<TextArea fx:id="ta" layoutX="50.0" layoutY="133.0" prefHeight="89.0" prefWidth="273.0" />
</children>
</AnchorPane>
And here is the stacktarce of the error
Exception in thread "JavaFX Application Thread" java.time.DateTimeException: Field DayOfYear cannot be printed as the value 196 exceeds the maximum print width of 2
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2548)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
at javafx.datepicker.DatePickerController$1.toString(DatePickerController.java:45)
at javafx.datepicker.DatePickerController$1.toString(DatePickerController.java:37)
at com.sun.javafx.scene.control.skin.ComboBoxPopupControl.updateDisplayNode(ComboBoxPopupControl.java:424)
at com.sun.javafx.scene.control.skin.DatePickerSkin.handleControlPropertyChanged(DatePickerSkin.java:141)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase.lambda$registerChangeListener$61(BehaviorSkinBase.java:197)
at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:361)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.ComboBoxBase.setValue(ComboBoxBase.java:150)
at com.sun.javafx.scene.control.skin.DatePickerContent.selectDayCell(DatePickerContent.java:689)
at com.sun.javafx.scene.control.skin.DatePickerContent.lambda$createDayCells$174(DatePickerContent.java:731)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
I tried almost every method to resolve this but always bad luck.
Please give me suggestions to resolve this and also explain this error.
I think you want the following:
String pattern = "dd-MM-yyyy";

How to solve Nullpoint in android

This is the code in MainActivity
MainActivity.java:541
#Override
public void onSaveInstanceState (Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("mCurrentChapter", mCurrentChapter);
savedInstanceState.putInt("index", mPager.getCurrentItem());
////Log.e("SaveInstance", mCurrentChapter + " " + mPager.getCurrentItem());
}
I don't see any problem.
java.lang.NullPointerException
at com.techexpert4u.duaaadhkaar.MainActivity.onSaveInstanceState(MainActivity.java:541)
at android.app.Activity.performSaveInstanceState(Activity.java:1153)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3175)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3234)
at android.app.ActivityThread.access$1100(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1223)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

Android: java.lang.nullPointerException at custom ListView adapter

I'm trying to make a custom view for my ListView, but the app crash when try to open it. I read a lot of pages but don't find the solution. Please help me!
This is my custom Adapter:
public class AdaptadorCatalogo extends BaseAdapter {
protected Activity activity;
protected ArrayList<LineaCatalogo> items;
public AdaptadorCatalogo(Activity activity, ArrayList<LineaCatalogo> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup parent) {
View vi=contentView;
if(contentView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.listitem_catalogo, null);
}
LineaCatalogo item = items.get(position);
TextView primeraLinea = (TextView) vi.findViewById(R.id.lblPrimeraLinea);
primeraLinea.setText(item.getPrimeraLinea());
TextView segundaLinea = (TextView) vi.findViewById(R.id.lblSegundaLinea);
segundaLinea.setText(item.getSegundaLinea());
TextView magnitud = (TextView) vi.findViewById(R.id.lblMagnitud);
magnitud.setText(item.getMagnitud());
return vi;
}
}
This is my 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"
tools:context=".listaSismos" >
<RelativeLayout
android:id="#+id/general"
style="#style/AppCentral"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="50dp" >
<TextView
android:id="#+id/titulo_catalogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="#string/esperando_info" />
<ListView
android:id="#+id/listaDatos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp" />
</RelativeLayout>
</RelativeLayout>
This is my Activity:
public class listaSismos extends Activity {
private TextView tituloCatalogo;
private ListView listaDatos;
private String opcion;
private String codigoUsuario;
private String latitud;
private String longitud;
private String idioma;
private int difHoraria;
private ArrayList<LineaCatalogo> Catalogo;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_sismos);
tituloCatalogo = (TextView)findViewById(R.id.titulo_catalogo);
listaDatos = (ListView)findViewById(R.id.listaDatos);
Bundle bundle = getIntent().getExtras();
opcion = bundle.getString("lista");
codigoUsuario = bundle.getString("codigoUsuario");
latitud = bundle.getString("latitud");
longitud = bundle.getString("longitud");
idioma = getResources().getConfiguration().locale.toString();
TimeZone defaultTZ = TimeZone.getDefault();
difHoraria = defaultTZ.getRawOffset() / 1000;
ListarCatalogo conexion = new ListarCatalogo();
conexion.execute();
}
#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;
}
private class ListarCatalogo extends AsyncTask<String,Integer,Boolean> {
private int contador;
protected Boolean doInBackground(String... params) {
boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
HttpGet del =
new HttpGet(my_app_server_url);
del.setHeader("content-type", "application/json");
try
{
HttpResponse resp = httpClient.execute(del);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
contador = respJSON.length();
for(int cont=0; cont<contador; cont++)
{
JSONObject obj = respJSON.getJSONObject(cont);
String tituloS = obj.getString("P");
String subtituloS = obj.getString("S");
String magnitudS = obj.getString("M");
Catalogo.add(new LineaCatalogo(tituloS, subtituloS, magnitudS));
}
}
catch(Exception ex)
{
resul = false;
}
return resul;
}
protected void onPostExecute(Boolean result) {
tituloCatalogo.setText(R.string.titulo_catalogo);
if (result)
{
//Rellenamos la lista con los resultados
AdaptadorCatalogo adaptador = new AdaptadorCatalogo(listaSismos.this, Catalogo);
listaDatos.setAdapter(adaptador);
tituloCatalogo.setText("OK");
} else {
tituloCatalogo.setText(R.string.no_datos);
}
}
}
}
If i comment the line "listaDatos.setAdapter(adaptador);", the app runs ok. If not, i get this LogCat:
12-06 09:34:32.443: W/dalvikvm(903): threadid=1: thread exiting with uncaught exception (group=0x41465700)
12-06 09:34:32.559: E/AndroidRuntime(903): FATAL EXCEPTION: main
12-06 09:34:32.559: E/AndroidRuntime(903): java.lang.NullPointerException
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.AdaptadorCatalogo.getCount(AdaptadorCatalogo.java:23)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.widget.ListView.setAdapter(ListView.java:463)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:124)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:1)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.finish(AsyncTask.java:631)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Handler.dispatchMessage(Handler.java:99)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Looper.loop(Looper.java:137)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invokeNative(Native Method)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invoke(Method.java:525)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-06 09:34:32.559: E/AndroidRuntime(903): at dalvik.system.NativeStart.main(Native Method)
I still working a week looking for the solution, but i can't do it. Please, help me. And sorry by my poor english, i'm spanish from Canary Islands.
Declare and initialize like
private ArrayList<LineaCatalogo> Catalogo= new ArrayList<LineaCatalogo>();
#Override
public void onCreate(Bundle savedInstanceState){
Remove
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
// becomes local to doInbackground as it is declared and initialized there.
in doInbackground.
In your case Catalogo was null.
You redefine your list with
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
in the doInBacground
use just
Catalogo = new ArrayList<LineaCatalogo>();

How to avoid java.lang.IllegalStateException: Could not execute method of the activity

In My project I am interacting with data bases, I has a button when pressed adds three items from three different edittexts such as name(string), idcardno(int of maximum 4nos), phoneno(int of max 10nos). On pressing Add button it makes exeception as below..
09-19 01:28:31.491: E/AndroidRuntime(1160): FATAL EXCEPTION: main
09-19 01:28:31.491: E/AndroidRuntime(1160): java.lang.IllegalStateException: Could not execute method of the activity
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.view.View$1.onClick(View.java:3633)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.view.View.performClick(View.java:4240)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.view.View$PerformClick.run(View.java:17721)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.os.Handler.handleCallback(Handler.java:730)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.os.Looper.loop(Looper.java:137)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.reflect.Method.invoke(Method.java:525)
09-19 01:28:31.491: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-19 01:28:31.491: E/AndroidRuntime(1160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-19 01:28:31.491: E/AndroidRuntime(1160): at dalvik.system.NativeStart.main(Native Method)
09-19 01:28:31.491: E/AndroidRuntime(1160): Caused by: java.lang.reflect.InvocationTargetException
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.reflect.Method.invoke(Method.java:525)
09-19 01:28:31.491: E/AndroidRuntime(1160): at android.view.View$1.onClick(View.java:3628)
09-19 01:28:31.491: E/AndroidRuntime(1160): ... 11 more
09-19 01:28:31.491: E/AndroidRuntime(1160): Caused by: java.lang.NumberFormatException: Invalid int: "4233494398"
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.Integer.invalidInt(Integer.java:138)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.Integer.parse(Integer.java:378)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.Integer.parseInt(Integer.java:366)
09-19 01:28:31.491: E/AndroidRuntime(1160): at java.lang.Integer.parseInt(Integer.java:332)
09-19 01:28:31.491: E/AndroidRuntime(1160): at com.wordpress.smdaudhilbe.database.MainActivity.addData(MainActivity.java:59)
09-19 01:28:31.491: E/AndroidRuntime(1160): ... 14 more
09-19 01:28:34.340: I/Process(1160): Sending signal. PID: 1160 SIG: 9
Here is my complete code,
package com.wordpress.smdaudhilbe.database;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity {
public EditText nameField,idCardField,phoneField;
public Button add,del,update;
public Spinner spN;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
spN.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
nameField.setText(parent.getItemAtPosition(position - 1).toString());
idCardField.setText(parent.getItemAtPosition(position).toString());
phoneField.setText(parent.getItemAtPosition(position+1).toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void addData(View v) {
initViews();
DataBaseHelper dbH = new DataBaseHelper(getApplicationContext());
dbH.insertContact(nameField.getText().toString(),Integer.parseInt(idCardField.getText().toString()),Integer.parseInt(phoneField.getText().toString()));
loadSpinner();
return;
}
private void loadSpinner() {
initViews();
DataBaseHelper dbH = new DataBaseHelper(getApplicationContext());
List<String> label = dbH.getIds();
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,label);
spN.setAdapter(adpt);
}
public void deleteData(View v) {
initViews();
DataBaseHelper dbH = new DataBaseHelper(getApplicationContext());
dbH.deleteContact(Integer.parseInt(idCardField.getText().toString()));
}
private void initViews(){
nameField = (EditText)findViewById(R.id.editText1name);
idCardField = (EditText)findViewById(R.id.editText2idcard);
phoneField = (EditText)findViewById(R.id.editText3phone);
add = (Button)findViewById(R.id.button1);
del = (Button)findViewById(R.id.button2);
update = (Button)findViewById(R.id.button3);
spN = (Spinner)findViewById(R.id.spinner1);
}
}
class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context context) {
super(context,"MyDataBase", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table contacts(name text not null,idCard integer,phoneNumber integer(10));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists contacts;");
}
public void insertContact(String name,int idcard,int phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put("name",name);
vals.put("idCard", idcard);
vals.put("phoneNumber", phone);
db.insert("contacts", null, vals);
db.close();
}
public void deleteContact(long idcard) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("contacts", "idCard=?",new String[] {String.valueOf(idcard)});
db.close();
}
public List<String> getIds() {
SQLiteDatabase db = this.getReadableDatabase();
List<String> lst = new ArrayList<String>();
Cursor cursor = db.rawQuery("select * from contacts;",null);
if(cursor.moveToFirst()){
do{
lst.add(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return lst;
}
}
How to solve this...? Kindly help, I read many are pointing to null pointer exception for this kind of problem.
for your information my main_activity.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".MainActivity" >
<EditText
android:id="#+id/editText1name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2idcard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:digits="0123456789"
android:maxLength="4" />
<EditText
android:id="#+id/editText3phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:digits="0123456789"
android:maxLength="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:onClick="addData" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="del"
android:onClick="deleteData"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
android:onClick="updateData"/>
</LinearLayout>
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
UPDATE:
When I put try - catch around
try{
dbH.insertContact(nameField.getText().toString(),Integer.parseInt(idCardField.getText().toString()),Integer.parseInt(phoneField.getText().toString()));
}catch (Exception e){e.printStackTrace();}
of addData() method,
I got this,
09-19 02:33:39.485: E/AndroidRuntime(933): FATAL EXCEPTION: main
09-19 02:33:39.485: E/AndroidRuntime(933): java.lang.NullPointerException
09-19 02:33:39.485: E/AndroidRuntime(933): at com.wordpress.smdaudhilbe.database.MainActivity$1.onItemSelected(MainActivity.java:41)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.widget.AdapterView.access$200(AdapterView.java:49)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.os.Handler.handleCallback(Handler.java:730)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.os.Looper.loop(Looper.java:137)
09-19 02:33:39.485: E/AndroidRuntime(933): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-19 02:33:39.485: E/AndroidRuntime(933): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 02:33:39.485: E/AndroidRuntime(933): at java.lang.reflect.Method.invoke(Method.java:525)
09-19 02:33:39.485: E/AndroidRuntime(933): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-19 02:33:39.485: E/AndroidRuntime(933): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-19 02:33:39.485: E/AndroidRuntime(933): at dalvik.system.NativeStart.main(Native Method)
09-19 02:33:42.555: I/Process(933): Sending signal. PID: 933 SIG: 9
I don't think, I made any error. using initViews() method,
private void initViews(){
nameField = (EditText)findViewById(R.id.editText1name);
idCardField = (EditText)findViewById(R.id.editText2idcard);
phoneField = (EditText)findViewById(R.id.editText3phone);
add = (Button)findViewById(R.id.button1);
del = (Button)findViewById(R.id.button2);
update = (Button)findViewById(R.id.button3);
spN = (Spinner)findViewById(R.id.spinner1);
}
I had already initialised all fields
and also I made every field as public.
public EditText nameField,idCardField,phoneField;
public Button add,del,update;
public Spinner spN;
Please help in this to trace the reason.

MediaPlayer+SurfaceView app fails

Uploaded an example from /samples/android-16 >/ApiDemos.
There's a few examples in a single project.
Extracted from there one-MediaPlayerDemo_Video, like so:
Mediaplayer_video.java
package com.example.mediaplayer_video;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class Mediaplayer_video extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "MediaPlayerVideo";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private static final String MEDIA = "media";
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
path = "sdcard/scheen.mp4";
if (path == "") {
// Tell the user to provide a media file URL.
Toast
.makeText(
Mediaplayer_video.this,
"Please edit Mediaplayer_Video Activity, "
+ "and set the path variable to your media file path."
+ " Your media file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
mediaplayer_2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Mediaplayer_video" >
<SurfaceView
android:id="#+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
</SurfaceView>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mediaplayer_video"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.mediaplayer_video.Mediaplayer_video"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Falls with this logo:
07-20 17:54:04.597: E/Trace(5713): error opening trace file: No such file or directory (2)
07-20 17:54:07.006: D/MediaPlayerVideo(5713): surfaceCreated called
07-20 17:54:07.106: D/AndroidRuntime(5713): Shutting down VM
07-20 17:54:07.106: W/dalvikvm(5713): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
07-20 17:54:07.236: E/AndroidRuntime(5713): FATAL EXCEPTION: main
07-20 17:54:07.236: E/AndroidRuntime(5713): java.lang.NullPointerException
07-20 17:54:07.236: E/AndroidRuntime(5713): at com.example.mediaplayer_video.Mediaplayer_video.surfaceCreated(Mediaplayer_video.java:128)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.SurfaceView.updateWindow(SurfaceView.java:543)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.SurfaceView.access$000(SurfaceView.java:81)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:671)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1820)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.Choreographer.doFrame(Choreographer.java:525)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.os.Handler.handleCallback(Handler.java:615)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.os.Handler.dispatchMessage(Handler.java:92)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.os.Looper.loop(Looper.java:137)
07-20 17:54:07.236: E/AndroidRuntime(5713): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-20 17:54:07.236: E/AndroidRuntime(5713): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 17:54:07.236: E/AndroidRuntime(5713): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 17:54:07.236: E/AndroidRuntime(5713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-20 17:54:07.236: E/AndroidRuntime(5713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-20 17:54:07.236: E/AndroidRuntime(5713): at dalvik.system.NativeStart.main(Native Method)
There are thoughts, what's up?
I found out what was my mistake.
The log indicates the line 128:
07-20 17:54:07.236: E/AndroidRuntime(5713): java.lang.NullPointerException
07-20 17:54:07.236: E/AndroidRuntime(5713): at com.example.mediaplayer_video.Mediaplayer_video.surfaceCreated(Mediaplayer_video.java:128)
At line 128 Mediaplayer_video.java this:
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
PlayVideo() method defined as playVideo(Integer Media), and Media = null.
Fixed the playVideo(Integer Media) and playVideo(extras.getInt(MEDIA)) on playVideo() and everything earned.