RuntimeException by using Google Youtube Api v3 in my android app - java

I want to get the list of videos from Youtube channel.
You will see below the class to connect to Youtube and my Activity that interacts with this class. I get an exception "java.lang.RuntimeException: Unable to start activity VideoListActivity" when calling YouTube.Search.List.execute();
I am new in android, so I think there is a stupid mistake. Please help to find it, or maybe suggest the another way to get data from Youtube.
YoutubeConnector class
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class YoutubeConnector {
private static YouTube youtube;
private static YouTube.Search.List query;
public static final String KEY = DeveloperKey.DEVELOPER_KEY;
public static List<VideoItem> search() throws IOException {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {
}
}).setApplicationName(R.string.app_name).build();
query = youtube.search().list("id,snippet");
query.setKey(KEY);
query.setType("video");
query.setChannelId("**************");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
List<VideoItem> items = new ArrayList<VideoItem>();
for (SearchResult result : results) {
VideoItem item = new VideoItem();
item.setTitle(result.getSnippet().getTitle());
item.setDescription(result.getSnippet().getDescription());
item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
item.setId(result.getId().getVideoId());
items.add(item);
}
return items;
}
}
VideoListActivity class
public class VideoListActivity extends ListActivity{
List<VideoItem> videoFileList;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
setListAdapter(new VideoAapter(VideoListActivity.this, R.layout.list_item_video, videoFileList));
}
}
Logcat
06-16 18:14:56.926 30817-30817/com.example.alex.youtubecanal W/art: Failed to find OatDexFile for DexFile /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex ( canonical path /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex) with checksum 0x7eb43558 in OatFile /data/data/com.example.alex.youtubecanal/cache/slice-slice_5-classes.dex
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isShipBuild true
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SMARTBONDING_FEATURE_ENABLED is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal D/AndroidRuntime: Shutting down VM
06-16 18:14:57.641 30817-30817/com.example.alex.youtubecanal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.youtubecanal, PID: 30817
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.alex.youtubecanal/com.example.alex.youtubecanal.VideoListActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:245)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:128)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.alex.youtubecanal.YoutubeConnector.search(YoutubeConnector.java:37)
at com.example.alex.youtubecanal.VideoListActivity.onCreate(VideoListActivity.java:58)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6917) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

You need to run the YoutubeConnector.search outside of onCreate() in an Async Thread. This basically means that the method is stalling the program and will cause the program to crash or hang. To fix, create a new class called Search for example:
SearchClass.java:
import android.os.AsyncTask;
import java.io.IOException;
public class Search extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String a){
VideoListActivity.context.updateAdapter();
}
}
VideoListActivity.java:
public class VideoListActivity extends ListActivity{
static List<VideoItem> videoFileList;
static Context context;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Search search= new Search();
search.execute(new String[]{});
}
public void updateAdapter(ArrayList<String> list) {
setListAdapter(new VideoAapter(VideoListActivity.this,R.layout.list_item_video, videoFileList));
}
}
Hopefully this will work :). If it does not, just post the error, and we'll get back. Good luck!

It looks like the problem is coming from a NetworkOnMainThreadException. Check out this example. Hope it helps!

Related

Unable to insert documents into mongodb database gives NetworkOnMainthread EXception

Im making an android app to fetch data from user and store it in a mongodb database
mongodb runs on localhost:27017 and im able to connect to it using 10.0.3.2:27017 on genymotion emulator
here is LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
static DB db;
static DBCollection locations;
public String name,middlename,surname,userid,profilelink,imageUrl,emailid,gender,birthday;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("JSON",response.toString());
try {
emailid=object.getString("email");
gender=object.getString("gender");
birthday=object.getString("birthday");
TextView nameView6 = (TextView)findViewById(R.id.emailr);
nameView6.setText(emailid);
TextView nameView7 = (TextView)findViewById(R.id.genderr);
nameView7.setText(gender);
TextView nameView8 = (TextView)findViewById(R.id.birthdayr);
nameView8.setText(birthday);
String[] dset={emailid,gender,birthday};
yalla(dset);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_birthday");
loginButton.registerCallback(callbackManager, callback);
}
#Override
protected void onResume() {
super.onResume();
//Facebook login
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
}
#Override
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
private void nextActivity(Profile profile){
if(profile != null){
Intent main = new Intent(LoginActivity.this, MainActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("middlename", profile.getMiddleName());
main.putExtra("surname", profile.getLastName());
main.putExtra("userid", profile.getId());
main.putExtra("profilelink", profile.getLinkUri());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
}
}
public static void yalla(String[] args){
String[] dset;
dset=args;
//try {
String uri = "mongodb://10.0.3.2:27017";
Log.v("enterhere", dset[0]);
MongoClientURI mongoClientURI=new MongoClientURI(uri);
//MongoClient mongoClient = new MongoClient("mongodb://10.0.3.2:27017/test");
Log.v("connectedserver", dset[0]);
MongoClient mongoClient = new MongoClient(mongoClientURI);
MongoDatabase database = mongoClient.getDatabase("users");
Log.v("Connect to database successfully",database.getName());
MongoCollection mongoCollection = database.getCollection("assest");
Log.v("collection", dset[0]);
Document doc = new Document("emailid", dset[0])
.append("gender", dset[1])
.append("birthday", dset[2]);
Log.v("document update", dset[0]);
mongoCollection.insertOne(doc);
Log.v("doc insertion", dset[0]);
mongoClient.close();
//} catch (MongoException e)
//{
// e.getStackTrace();
//}
}
}
Error on android studio
V/document update: zissujith#gmail.com
I/cluster: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=10.0.3.2:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
I/connection: Opened connection [connectionId{localValue:1, serverValue:17}] to 10.0.3.2:27017
I/cluster: Monitor thread successfully connected to server with description ServerDescription{address=10.0.3.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 14]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=9233253}
D/dalvikvm: GC_CONCURRENT freed 413K, 5% free 12382K/12935K, paused 11ms+1ms, total 17ms
I/connection: Closed connection [connectionId{localValue:2}] to 10.0.3.2:27017 because the underlying connection was closed.
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62fe288)
E/AndroidRuntime: FATAL EXCEPTION: main
com.mongodb.MongoException: android.os.NetworkOnMainThreadException
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:125)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80)
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
at com.mongodb.Mongo.execute(Mongo.java:747)
at com.mongodb.Mongo$2.execute(Mongo.java:730)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224)
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46) 
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80) 
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69) 
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86) 
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184) 
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72) 
at com.mongodb.Mongo.execute(Mongo.java:747) 
at com.mongodb.Mongo$2.execute(Mongo.java:730) 
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482) 
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277) 
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224) 
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99) 
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304) 
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
You can use Async Task for this. I don't know much about mongoDB, but assuming your yalla method has heavy network operation which includes mongoDB.
Try to add yalla method into new AyancTask.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//Include your mongoDB accessing method here, in background thread.
}
}
And you can execute this method by the following line from your activity.
new DownloadFilesTask().execute(url1, url2, url3);
Hope this helps.
EDIT: Now you are including your method in AsyncTask, and passing URL as arguments, Just provide the links via execute() method. No need to use this String[] = args, which currently you are using in your methos.
For more details on AsyncTask, refer the official docs from this link :)
I am actually trying to do the same and found mongoclient won't work so I used the common class to connect to my server on mlab then I used an asynkTask inner class with HTTPUrlConnection to get the data I stored, check out this link for querying urls for mlab-> http://docs.mlab.com/data-api/
Also check this out-> https://m.youtube.com/watch?v=RSZ2pyhfR0I
public class Common {
private static String DB_NAME = "edmtdev";
private static String COLLECTION_NAME = "user";
public static String API_KEY = "YOUR API KEY";
public static String getAddressSingle(User user) {
String baseUrl = String.format("https://api.mlab.com/api/1/databases/%s/collections/%s", DB_NAME, COLLECTION_NAME);
StringBuilder stringBuilder = new StringBuilder(baseUrl);
stringBuilder.append("/"+user.get_id().getOid()+"?apiKey="+API_KEY);
return stringBuilder.toString():
}

Check File Extension in android

i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed.
Here is Code:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView filecheck;
filecheck = (TextView) findViewById(R.id.filecheck);
filecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (accept()) {
Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean accept() {
final File pathname = new File("/sdcard/test/");
String files[] = pathname.list();
System.out.println(files.length);
for (String s : files) {
if (s.contains(".mp4")) {
System.out.println(s);
return true;
}
return false;
}
return false;
}
}
Here is exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: jss.testmethods, PID: 23659
java.lang.NullPointerException
at jss.testmethods.MainActivity.accept(MainActivity.java:38)
at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4478)
at android.view.View$PerformClick.run(View.java:18698)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
i was expecting simple error, i missed to add permission for read storage. it is working now.

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

Android Activity has a FATAL EXCEPTION: AsyncTask #1 and has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView

I'm new at android programming, I want to fetch Parse in ListView arrangement and i found the perfect guide, but i cant really implement it on my code.
I have browse a lot for 2 days and i give up.
Here's the error
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.osbert.buttons, PID: 2732
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1048)
at com.parse.ParseUser.access$900(ParseUser.java:27)
at com.parse.ParseUser$9.then(ParseUser.java:1041)
at com.parse.ParseUser$9.then(ParseUser.java:1038)
at com.parse.TaskQueue.enqueue(TaskQueue.java:61)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1038)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1001)
at com.parse.ParseQuery.getUserAsync(ParseQuery.java:352)
at com.parse.ParseQuery.access$1600(ParseQuery.java:78)
at com.parse.ParseQuery$15.call(ParseQuery.java:1000)
at com.parse.ParseQuery$15.call(ParseQuery.java:997)
at com.parse.ParseQuery.doWithRunningCheck(ParseQuery.java:936)
at com.parse.ParseQuery.findInBackground(ParseQuery.java:997)
at com.parse.ParseQuery.find(ParseQuery.java:588)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:60)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            
E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.osbert.buttons.RestaurantList has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{27bb5583 V.E..... R......D 0,0-729,322} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.onPreExecute(RestaurantList.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.osbert.buttons.RestaurantList.onCreate(RestaurantList.java:30)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
And here's my code
package com.example.osbert.buttons;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class RestaurantList extends Activity {
// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<WorldPopulation> worldpopulationlist = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RestaurantList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Country");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("ranknum");
ob = query.find();
for (ParseObject country : ob) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("flag");
WorldPopulation map = new WorldPopulation();
map.setRank((String) country.get("rank"));
map.setCountry((String) country.get("country"));
map.setPopulation((String) country.get("population"));
map.setFlag(image.getUrl());
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(RestaurantList.this,
worldpopulationlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
finish();
}
}
}
Pls help :((
Thanks in advance
Have you even tried resolving this?
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library?
Its the cause of the crash.
Also why are you calling finish() i onPostExecute?! It will close your activity...and i suppose you would like to see the results in your list view?
U error Logs says the solution.....
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)

Having trouble passing variable to be displayed on a screen on android

I am having trouble with developing my Android application, I am currently using Eclipse and a Phidget RFID. My aim is to display the ID of the RFID in a piece of text on the Android device.
I have managed to display the ID through a println in the following pieces of code.
package myFood.myFood;
import com.phidgets.*;
import com.phidgets.event.*;
public class RFID {
static String x ="NULL";
public static final Object main(String args[]) throws Exception {
RFIDPhidget rfid;
rfid = new RFIDPhidget();
rfid.openAny();
//Begin the TagGained event, allowing for users to read the RFID values
rfid.addTagGainListener(new TagGainListener()
{
public void tagGained(TagGainEvent oe)
{
Object y = (oe.getValue());
x= y.toString();
}
});
long StartTime,RunTime;
StartTime=System.currentTimeMillis();
do{
RunTime=System.currentTimeMillis();
if (x.equals("NULL")) {
//Continue waiting for input
}
else
StartTime = 10000; //Overload the result so the loop ends
}
while (RunTime-StartTime<5000);
rfid.close();
return x;
}
}
and then.
package myFood.myFood;
public class RFIDresult {
public static final Object main(String args[]) throws Exception {
System.out.println("Results");
Object x = RFID.main(args);
System.out.println(x);
return x;
}
}
However I want the ID to be displayed in a piece of text so I tried to develop the second piece of code into Android.
package myFood.myFood;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddFood extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addfood);
Button mybutton = (Button) findViewById(R.id.Button1);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String[] args = null;
Object x = null;
try {
x = RFID.main(args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView mytext=(TextView)findViewById(R.id.widget96);
mytext.setText((CharSequence) x);
}
});
}
}
And this just generates a force close. I am a bit of a novice at this and will appreciate all the advice I get.
LogCat Report;
ERROR/AndroidRuntime(519): FATAL EXCEPTION: main
ERROR/AndroidRuntime(519): java.lang.ExceptionInInitializerError
ERROR/AndroidRuntime(519): at myFood.myFood.RFID.main(RFID.java:9)
ERROR/AndroidRuntime(519): at myFood.myFood.AddFood$1.onClick(AddFood.java:26)<br/>
ERROR/AndroidRuntime(519): at android.view.View.performClick(View.java:2408)
ERROR/AndroidRuntime(519): at android.view.View$PerformClick.run(View.java:8816)
ERROR/AndroidRuntime(519): at android.os.Handler.handleCallback(Handler.java:587)
ERROR/AndroidRuntime(519): at android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/AndroidRuntime(519): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(519): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(519): at om.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
ERROR/AndroidRuntime(519): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
ERROR/AndroidRuntime(519): at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(519): Caused by: java.lang.ExceptionInInitializerError: Library phidget21 not found
ERROR/AndroidRuntime(519): Could not locate the Phidget C library (libphidget21.so).
ERROR/AndroidRuntime(519): Make sure it is installed, and add it's path to LD_LIBRARY_PATH.
ERROR/AndroidRuntime(519): at com.phidgets.Phidget.<clinit>(Phidget.java:34)
ERROR/AndroidRuntime(519): ... 13 more
You need to get myText from 'view' parameter. Try this:
TextView mytext=(TextView)**view**.findViewById(R.id.widget96);

Categories