setMediaController中的onCreate错误

时间:2014-05-10 22:59:24

标签: android

我有2个简单的工作应用程序,我正在尝试结合。 #1从我指定的URL播放视频视频中的视频,#2从数据库加载信息。我只是想将视频视图放在与从数据库加载的信息相同的区域中。

视频视图显示在正确的位置,但是当我在onCreate中的任何位置添加此代码时应用程序崩溃:

    // **NEW VIDEOVIEW CODE**
    VideoView vid = (VideoView) findViewById(R.id.videoView);
    Uri video = Uri.parse(MOVIE_URL);
    vid.setMediaController(new MediaController(this));
    vid.setVideoURI(video);
    vid.start();
    vid.requestFocus();

通过反复试验,我确定它从“setMediaController”行开始崩溃。这是onCreate(没有上面的代码就可以正常工作,显然除了空白视频外):

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();



    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });



}

这是logcat:

05-10 15:33:29.064: I/Adreno-EGL(7866): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
05-10 15:33:29.084: D/OpenGLRenderer(7866): Enabling debug mode 0
05-10 15:33:30.214: D/AndroidRuntime(7866): Shutting down VM
05-10 15:33:30.214: W/dalvikvm(7866): threadid=1: thread exiting with uncaught exception (group=0x41898ba8)
05-10 15:33:30.214: E/AndroidRuntime(7866): FATAL EXCEPTION: main
05-10 15:33:30.214: E/AndroidRuntime(7866): Process: com.example.androidhive, PID: 7866
05-10 15:33:30.214: E/AndroidRuntime(7866): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidhive/com.example.androidhive.AllProductsActivity}: java.lang.NullPointerException
05-10 15:33:30.214: E/AndroidRuntime(7866):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

总之,我正在试图弄清楚我是否会完全错误,或者是否有办法在不崩溃的情况下包含此代码。谢谢!

编辑我很抱歉没有发布这些内容,我只是不想压倒人。

这是我的list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
    android:id="@+id/pid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />


<!-- Name Label -->
<TextView
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="6dip"
    android:paddingLeft="6dip"
    android:textSize="17dip"
    android:textStyle="bold" />

    <TextView
    android:id="@+id/description"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="6dip"
    android:paddingLeft="6dip"
    android:textSize="17dip"
    android:textStyle="bold" />

    <VideoView
     android:id="@+id/videoView"
     android:layout_width="100dp"
     android:layout_height="100dp"
     />

</LinearLayout>

这是我的all_products.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView 
     Always give id value as list(@android:id/list)
-->
<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

最后......这是我的整个AllProductsActivity.java文件:

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.VideoView;

public class AllProductsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// get video url
private static final String MOVIE_URL ="http://mywebsite.com/mycameraapp/android_connect/videos/testvideo.mkv";

// url to get all products list
private static String url_all_products = "http://mywebsite.com/mycameraapp/android_connect/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // **NEW VIDEOVIEW CODE**
    VideoView vid = (VideoView) findViewById(R.id.videoView);
    Uri video = Uri.parse(MOVIE_URL);
    vid.setMediaController(new MediaController(this));
    vid.setVideoURI(video);
    vid.start();
    vid.requestFocus();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });



}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID, TAG_NAME, TAG_DESCRIPTION},
                        new int[] { R.id.pid, R.id.name,     R.id.description });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

1 个答案:

答案 0 :(得分:1)

您收到错误,因为 all_products.xml 文件中没有VideoView元素。

您需要做的是创建一个ListAdapter并让列表适配器的 getView()方法引用您的 list_item.xml 布局文件。这是包含VideoView的文件。