Looping through multiple xml, adding to listView - java

I have followed a tutorial which shows you how you can connect to an rss feed, and pull down the data into a listView. The problem is, is that I want to be able to loop through multiple feeds adding them to the same listView, but when I try to do this....it brings back the following logCat error.
If anyone can help me, that would be great thanks!
Code:
package com.androidhive.xmlparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
String[] URL = new String[2];
int count = 0;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssRun();
}
public void rssRun()
{
URL[0] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
URL[1] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < 2;f++)
{
count+=1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
if (count==2)
{
setListAdapter(adapter);
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
}
LogCat:
08-27 09:34:39.786: E/Error:(30651): Expected a quoted string (position:DOCDECL #1:50 in java.io.StringReader#42be4218)
08-27 09:34:39.786: D/AndroidRuntime(30651): Shutting down VM
08-27 09:34:39.786: W/dalvikvm(30651): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 09:34:39.786: E/AndroidRuntime(30651): FATAL EXCEPTION: main
08-27 09:34:39.786: E/AndroidRuntime(30651): Process: com.androidhive.xmlparsing, PID: 30651
08-27 09:34:39.786: E/AndroidRuntime(30651): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.os.Looper.loop(Looper.java:157)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 09:34:39.786: E/AndroidRuntime(30651): at dalvik.system.NativeStart.main(Native Method)
08-27 09:34:39.786: E/AndroidRuntime(30651): Caused by: java.lang.NullPointerException
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:57)
08-27 09:34:39.786: E/AndroidRuntime(30651): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:38)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Activity.performCreate(Activity.java:5426)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 09:34:39.786: E/AndroidRuntime(30651): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)

Related

Android display SD card files throws java.lang.NullPointerException

This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}

Unfortunately app has stopped working [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from JSON tutorial
AndroidJsonParsing.java
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
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.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
SingleMenuItemActivity.java
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Logcat
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
You are calling the following code from the main thread instead of
background thread therefore this exception is thrown .
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Instead create a async task and perform this in the doInBackground() of the async task
Async task performs the opertaion in background instead of performing it on the main /UI thread
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
In onCreate() call the execute the async task in the following way :
new FetchJsonTask().execute();
Related Link:
How to fix android.os.NetworkOnMainThreadException?
you have called the Web from main thread. that's why you have got
Caused by: android.os.NetworkOnMainThreadException
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!!
read commented parts and change your code according to that.
class MyAsync extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your JSON parse here
return null;
}
#Override
protected void onPostExecute(Void result) {
// after gettin json data do whatever you want here
super.onPostExecute(result);
}
}
call your async class in your oncreate as:
new MyAsync().execute();

Writing to excel file with apache poi in android project

I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..

nullpointerexception cannot start activity

I keep getting nullpointerexception errors when I try to start a second activity from my main activity, my main activity code goes as such:
package com.cep.daredevil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public boolean filled = true;
EditText taskArray[] = new EditText[200];
EditText descArray[] = new EditText[200];
String taskArr[] = new String[200];
String descArr[] = new String[200];
int taskId[] = new int[200];
int descId[] = new int[200];
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
Button addfield = new Button(this);
addfield.setText("+");
llayout.addView(addfield);
addfield.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
addtask();
}
});
for(int i=0;i<3;i++)
{
addtask();
}
LinearLayout blayout = (LinearLayout)findViewById(R.id.blayout);
Button submit = new Button(this);
submit.setText("Enter Dare");
Button viewdare = new Button(this);
viewdare.setText("View Dares");
blayout.addView(submit);
blayout.addView(viewdare);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
inputdare(null);
}
});
viewdare.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
listdare();
}
});
}
#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;
}
public void addtask()
{
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
taskArray[n] = new EditText(this);
taskArray[n].setHint("Task Title");
taskArray[n].setId(n+10000000);
taskArray[n].setPadding(26,30,25,8);
descArray[n] = new EditText(this);
descArray[n].setHint("Task Description");
descArray[n].setId(n+20000000);
llayout.addView(taskArray[n]);
llayout.addView(descArray[n]);
n++;
}
public void inputdare(View v){
EditText daretitle = (EditText)findViewById(R.id.title);
String dare = daretitle.getText().toString();
for (int i=0;i<n;i++)
{
if (taskArr[i] != null)
{
taskArr[i] = taskArray[i].getText().toString();
}
Integer id = taskArray[i].getId();
if (id != null)
{
taskId[i] = id;
}
}
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putStringArray("TASKS", taskArr);
bundle.putIntArray("TASKID", taskId);
bundle.putBoolean("INPUT", true);
intent.putExtras(bundle);
startActivity(intent);
}
}
public void listdare()
{
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putBoolean("INPUT", false);
intent.putExtras(bundle);
startActivity(intent);
}
}
the function that seems to be causing the problem is in my second activity, over here:
package com.cep.daredevil;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DisplayDares extends Activity {
public final static String PREFS = "Preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_dare);
setupActionBar();
Bundle bundle = getIntent().getExtras();
Boolean input = bundle.getBoolean("INPUT");
if (input == false){}
else
{
int[] taskId = bundle.getIntArray("TASKID");
final String[] taskArray = bundle.getStringArray("TASKS");
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
TextView test = (TextView)findViewById(taskId[0]);
test.setText(taskArray[1]);
layout.addView(test);
}
}
}
the error I get is this:
03-08 13:32:18.053: E/AndroidRuntime(6873): FATAL EXCEPTION: main
03-08 13:32:18.053: E/AndroidRuntime(6873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cep.daredevil/com.cep.daredevil.DisplayDares}: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Looper.loop(Looper.java:137)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invoke(Method.java:511)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-08 13:32:18.053: E/AndroidRuntime(6873): at dalvik.system.NativeStart.main(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:32)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Activity.performCreate(Activity.java:5104)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
After pasing your code it seems line 34 is:
layout.addView(test);
So this line generates a nullpointer exception
Check if the id of your layout is the same.
Tip:
Further in your error stacktrace you can see what causes the error:
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:34)
DisplayDares.java:34
Means line 34 in your DisplayDares.java file.
You will see it is the following line:
layout.addView(test);
Now test cannot be NULL because it wouldn't have thrown that error. So layout must be.

Music Player - Function doesn't work when trying to use objects

I am making a music player application for my Computing project. I got it working but found that using objects would get more more marks. As a result, I changed some of my code to incorporate the use of objects, but it doesn't work when I execute my application. Btw I am quite new to Java so it's possible I made a silly mistake.
When I used this code the function I tried to implement worked:
private void SongTitleEndTime(){
try {
TextViewSongTitle = (TextView)findViewById(R.id.songTitle);
if (id != 0 ){
String where = MediaStore.Audio.Media._ID + " = " + "'" + id + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID.toString(), MediaStore.Audio.Media.ALBUM_ID.toString()}, where , null,
null);
mCursor.moveToFirst();
String title = mCursor.getString(0);
String artist = mCursor.getString(1);
String name = title + " - " + artist;
TextViewSongTitle.setText(name);
String fulltime;
albumfullid = Long.parseLong(mCursor.getString(3));
TextView EndTime = (TextView) findViewById(R.id.endtime);
long Minutes = TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration());
long Seconds = TimeUnit.MILLISECONDS.toSeconds(mMediaPlayer.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration()));
if (Seconds < 10) {
String second = "0" + String.valueOf(Seconds);
fulltime = Minutes + ":" + second;
} else {
//else display as normal
fulltime = Minutes + ":" + Seconds;
}
EndTime.setText(fulltime);
//display the duration of song
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} //catch for errors
}
But when I tried this, I got an error:
Main Class:
private void SongTitleEndTime() {
try {
final TextView TextViewSongTitle = (TextView) findViewById(R.id.songTitle);
if (CurrentSongID != 0) {
final Song CurrentSong = new Song(CurrentSongID);
SongName = CurrentSong.SongName;
TextViewSongTitle.setText(SongName);
AlbumID = CurrentSong.AlbumID;
final TextView EndTime = (TextView) findViewById(R.id.endtime);
final String TotalSongDuration = CurrentSong.TotalDuration;
EndTime.setText(TotalSongDuration);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
Object Class:
package com.example.music.test;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
public class Song extends Activity {
private final String where;
public String SongName;
public long AlbumID;
public String TotalDuration;
public Song(final long SongID) {
where = MediaStore.Audio.Media._ID + " = " + "'" + SongID + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID.toString(),
MediaStore.Audio.Media.ALBUM_ID.toString() }, where, null, null);
mCursor.moveToFirst();
final String SongTitle = getSongTitle(mCursor);
final String SongArtist = getSongArtist(mCursor);
SongName = SongTitle + " - " + SongArtist;
AlbumID = getAlbumID(mCursor);
TotalDuration = getTotalDuration();
}
public String getSongTitle(final Cursor mCursor) {
final String songtitle = mCursor.getString(0);
return songtitle;
}
public String getSongArtist(final Cursor mCursor) {
final String songartist = mCursor.getString(1);
return songartist;
}
public long getAlbumID(final Cursor mCursor) {
final long AlbumID = Long.parseLong(mCursor.getString(3));
return AlbumID;
}
public String getTotalDuration() {
String TotalTime;
final long Minutes = TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration());
final long Seconds = TimeUnit.MILLISECONDS
.toSeconds(Player.mMediaPlayer.getDuration())
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration()));
if (Seconds < 10) {
final String second = "0" + String.valueOf(Seconds);
TotalTime = Minutes + ":" + second;
} else {
TotalTime = Minutes + ":" + Seconds;
}
return TotalTime;
}
}
The error I get is:
01-02 21:55:41.941: E/AndroidRuntime(717): FATAL EXCEPTION: main
01-02 21:55:41.941: E/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.music.test/com.example.music.test.Player}: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Looper.loop(Looper.java:137)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 21:55:41.941: E/AndroidRuntime(717): at dalvik.system.NativeStart.main(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): Caused by: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.managedQuery(Activity.java:1737)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Song.<init>(Song.java:21)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.SongTitleEndTime(Player.java:90)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.AllActivities(Player.java:80)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.onCreate(Player.java:66)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.performCreate(Activity.java:5008)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 21:55:41.941: E/AndroidRuntime(717): ... 11 more
Song is an Activity. Thus you can't call manageQuery before onCreate has been called. That's your error.

Categories

Resources