I have an issue with setting a bitmap in an Alert dialog. I created a barcode in another class and I want to show the barcode in a dialog. It keeps showing an error. From the logs, the barcode is being created successfully. The problem keeps pointing to the qrCodeImageView.setImageBitmap(bitmap); line. Please help.
This is the method in the activity.
public void showQRCode(final Bundle bundle){
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
barcodeUtil = new BarcodeUtil();
Bitmap bitmap = barcodeUtil.createQRCcode(ContactDetailActivity.this, bundle);
AlertDialog.Builder builder = new AlertDialog.Builder(ContactDetailActivity.this);
Log.i(Constants.TAG_GBACARD, "Bmp in Dialog: " + bitmap);
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.custom_dialog, null);
builder.setView(dialogLayout);
final ImageView qrCodeImageView = (ImageView) findViewById(R.id.qrCode);
qrCodeImageView.setImageBitmap(bitmap);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = builder.create();
b.show();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
This is the method that creates the barcode
public Bitmap createQRCcode(final Context context, final Bundle bundle) {
Bitmap bitmap = null;
try {
//Find screen size
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
//Encode with a QR Code image
qrCodeEncoder = new QRCodeEncoder(null,
bundle,
Contents.Type.CONTACT,
BarcodeFormat.QR_CODE.toString(),
smallerDimension);
bitmap = qrCodeEncoder.encodeAsBitmap();
Log.i(Constants.TAG_GBACARD, "QR Encoded");
Log.i(Constants.TAG_GBACARD, "Bitmap: " + bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
This is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity$10.run(ContactDetailActivity.java:336)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.app.Activity.runOnUiThread(Activity.java:5575)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity.showQRCode(ContactDetailActivity.java:316)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at newgbacard.gbacard.com.gbacard.activities.ContactDetailActivity$5.onClick(ContactDetailActivity.java:168)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.view.View.performClick(View.java:5184)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.view.View$PerformClick.run(View.java:20910)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.os.Looper.loop(Looper.java:145)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5942)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
10-22 08:51:36.491 10948-10948/newgbacard.gbacard.com.gbacard W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Please Help. Thanks
Please replace this
final ImageView qrCodeImageView = (ImageView) findViewById(R.id.qrCode);
with this
final ImageView qrCodeImageView = (ImageView) dialogLayout.findViewById(R.id.qrCode);
Related
I am developing an app that show all album image covers. But it crashes with this error:
11-10 18:08:48.148 16187-16187/com.xrobot.andrew.musicalbums E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 16187
java.lang.OutOfMemoryError: Failed to allocate a 1459276 byte allocation with 421736 free bytes and 411KB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:417)
at android.graphics.drawable.Drawable.createFromPath(Drawable.java:1230)
at com.xrobot.andrew.musictest2.SongAdapter.getView(SongAdapter.java:73)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.makeAndAddView(ListView.java:1875)
at android.widget.ListView.fillDown(ListView.java:702)
at android.widget.ListView.correctTooLow(ListView.java:1484)
at android.widget.ListView.fillGap(ListView.java:676)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5036)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4584)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Partial code in the onCreate method:
...
while(...){
String thisCover = getCoverArtPath(cursor.getLong(6), getApplicationContext());
songList.add(new Song(thisId, thisTitle, thisArtist, thisPath, thisDuration, thisCover));
}
SongAdapter songAdt = new SongAdapter(getApplicationContext(), songList);
...
Code that I use to get the album image cover:
private static String getCoverArtPath(long albumId, Context context) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String result = null;
if (queryResult) {
result = albumCursor.getString(0);
}
albumCursor.close();
return result;
}
Layout AlbumCover :
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/song_cover"
android:scaleType = "fitXY"
android:src="#drawable/note"
android:background="#171717"
android:padding="1dp"
android:layout_marginLeft="3dp" />
getView in the Adapter:
#Override
public View getView(View convertView, ViewGroup parent) {
RelativeLayout songLay = (RelativeLayout)songInf.inflate
(R.layout.song_layout, parent, false);
ImageView coverView = (ImageView)songLay.findViewById(R.id.song_cover);
//get song using position
Song currSong = songs.get(position);
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
coverView.setImageDrawable(img);
}
//set position as tag
songLay.setTag(position);
return songLay;
}
EDIT:
I have tryed glide as suggested, but I still get the same error:
if (Drawable.createFromPath(currSong.getCover()) != null) {
Drawable img = Drawable.createFromPath(currSong.getCover());
Glide.with(mContext).load("").placeholder(img).override(50,50).into(coverView);
}
This is the new error:
11-11 11:05:55.866 11120-11120/com.xrobot.andrew.musicalbumsE/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xrobot.andrew.musicalbums, PID: 11120
java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available
My app has a SQlite database that I am trying to populate at initial install from a server. I am using volley to connect and have a web service on the server side. My issue is that on the first install when I call the method to populate the database it is obviously running on a different thread so before finishing it is moving on the building the UI. The UI is populated from the database so because the database has not been fulling populated I get error.
I have tried to force the volley call to run synchronously but just get a timeout exception
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: java.util.concurrent.TimeoutException
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.volley.toolbox.RequestFuture.doGet(RequestFuture.java:121)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.volley.toolbox.RequestFuture.get(RequestFuture.java:97)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.network.ArmyNetworking.getTableFromServer(ArmyNetworking.java:93)
11-29 09:38:49.646 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.database.DataCreator.getDatabaseFromServer(DataCreator.java:1657)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.clashtoolkit.clashtoolkit.UI.ArmyBuilder.onCreate(ArmyBuilder.java:46)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
11-29 09:38:49.647 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.os.Looper.loop(Looper.java:135)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5257)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at java.lang.reflect.Method.invoke(Native Method)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
11-29 09:38:49.648 4206-4206/com.clashtoolkit.clashtoolkit W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I cannot figure out the best way to do this. The DB has to be populated first, but I cannot seem to stop the UI code from running before it has been populated.
Main.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_army_builder);
//create and populate the database
DataCreator dbCreate = new DataCreator();
dbCreate.getDatabaseFromServer(this);
//creates the Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new TroopPagerAdapter(getSupportFragmentManager(), titles, numberOfTabs);
//Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.army_pager);
pager.setOffscreenPageLimit(4);
pager.setAdapter(adapter);
//assigning the sliding tab layout view
tabs = (SlidingTabLayout) findViewById(R.id.army_tabs);
//creating the icon portion of the sliding tabs
tabs.setCustomTabView(R.layout.custom_tabs, R.id.tabText);
//Setting custom color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorPrimaryDark);
}
});
//Setting the ViewPager for the slidingtabsLayout
tabs.setViewPager(pager);
//Set the barracks fragments to the barracks viewpager
BuilderObjData builderObjData = new BuilderObjData();
ArrayList<Builder> barracksArray = builderObjData.getBuilderObjArray(this, Utilities.BUILDER_TYPE_BARRACKS);
bAdpter = new BarracksPagerAdapter(getSupportFragmentManager(), barracksArray);
bPager = (ViewPager) findViewById(R.id.barracks_pager);
bPager.setAdapter(bAdpter);
}
getDatabaseFromServer()
public void getDatabaseFromServer(Context context) {
Cursor cursor = context.getContentResolver().query(Container.CONTENT_URI, null, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
for (String table : DataCreator.TABLES) {
ArmyNetworking.getTableFromServer(table, context);
}
if (cursor != null) {
cursor.close();
}
}
}
getTableFromServer()
public static void getTableFromServer(final String tableName, final Context context) {
Log.d(TAG, "called now");
String url = ArmyNetworking.WEB_BASE_URL + ArmyNetworking.PATH_TABLE + "/" + tableName;
// RequestFuture<JSONArray> future = RequestFuture.newFuture();
// JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, future, future);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url,
(String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
updateTableFromServer(response, context, tableName);
Log.d(TAG, "got response");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//add error handling
}
});
VolleySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
// try {
// JSONArray response = future.get(30, TimeUnit.SECONDS);
// updateTableFromServer(response, context, tableName);
//
// } catch (InterruptedException | ExecutionException | TimeoutException e) {
// e.printStackTrace();
// }
}
The above method shows the two different ways I tried to make the Volley call. The commented out code is to force it to be synchronous
Just add another activity at the start of your program, which shows a progress bar and a text like "Please wait while the data is loaded from the network, or check out our competitors' apps in the meantime".
I currently am trying to pull down an RSS Feed as an XML file and I'm trying to use RXJava instead of an AsyncTask to parse and download the file.
I'm getting a network on the main thread error though while I'm trying to pull the feed down.
Here is the relevant code with observable which is in the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final ArrayList<TestItem> testItems = new ArrayList<>();
//testItems.add(new TestItem("Title here", "Content here"));
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
// Subscribe on a new background thread, while returning the result on the UI thread.
// Using the RSS Classes we will pull the rss items from the rss feed and then create our
// own TestItem from them.
try {
Observable
.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
TestItemAdapter testItemAdapter = new TestItemAdapter(testItems);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(testItemAdapter);
And here is my RSSReader class
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
return handler.getRssItemList();
}
}
And my RSSHandler class
public class RssHandler extends DefaultHandler {
private List<RssItem> rssItemList;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
private boolean parsingDescription;
public RssHandler() {
//Initializes a new ArrayList that will hold all the generated RSS items.
rssItemList = new ArrayList<RssItem>();
}
public List<RssItem> getRssItemList() {
return rssItemList;
}
//Called when an opening tag is reached, such as <item> or <title>
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("item"))
currentItem = new RssItem();
else if (qName.equals("title"))
parsingTitle = true;
else if (qName.equals("link"))
parsingLink = true;
else if (qName.equals("description"))
parsingDescription = true;
else if (qName.equals("media:thumbnail") || qName.equals("media:content") || qName.equals("image")) {
if (attributes.getValue("url") != null)
currentItem.setImageUrl(attributes.getValue("url"));
}
}
//Called when a closing tag is reached, such as </item> or </title>
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("item")) {
//End of an item so add the currentItem to the list of items.
rssItemList.add(currentItem);
currentItem = null;
} else if (qName.equals("title"))
parsingTitle = false;
else if (qName.equals("link"))
parsingLink = false;
else if (qName.equals("description"))
parsingDescription = false;
}
//Goes through character by character when parsing whats inside of a tag.
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentItem != null) {
//If parsingTitle is true, then that means we are inside a <title> tag so the text is the title of an item.
if (parsingTitle)
currentItem.setTitle(new String(ch, start, length));
//If parsingLink is true, then that means we are inside a <link> tag so the text is the link of an item.
else if (parsingLink)
currentItem.setLink(new String(ch, start, length));
//If parsingDescription is true, then that means we are inside a <description> tag so the text is the description of an item.
else if (parsingDescription)
currentItem.setDescription(new String(ch, start, length));
}
}
}
Stack trace
10-07 11:39:15.040 1959-1959/? I/art: Late-enabling -Xcheck:jni
10-07 11:39:15.208 1959-1959/? W/System.err: java.io.IOException: Couldn't open http://www.feedforall.com/sample.xml
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.rss.RssReader.getItems(RssReader.java:36)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.ui.MainActivity.onCreate(MainActivity.java:47)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Looper.loop(Looper.java:135)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
10-07 11:39:15.208 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-07 11:39:15.209 1959-1959/? W/System.err: Caused by: android.os.NetworkOnMainThreadException
10-07 11:39:15.209 1959-1959/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
10-07 11:39:15.209 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
10-07 11:39:15.209 1959-1959/? W/System.err: ... 18 more
10-07 11:39:15.209 1959-1959/? E/App: Failed to download RSS Items
10-07 11:39:15.215 1959-1978/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-07 11:39:15.216 1959-1959/? D/: HostConnection::get() New Host Connection established 0xb42d9a00, tid 1959
10-07 11:39:15.219 1959-1959/? D/Atlas: Validating map...
10-07 11:39:15.281 1959-1978/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
10-07 11:39:15.282 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-07 11:39:15.286 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
10-07 11:39:15.295 1959-1978/? D/: HostConnection::get() New Host Connection established 0xb42d9b90, tid 1978
10-07 11:39:15.311 1959-1978/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-07 11:39:15.360 1959-1978/? D/OpenGLRenderer: Enabling debug mode 0
10-07 11:39:15.381 1959-1978/? W/EGL_emulation: eglSurfaceAttrib not implemented
10-07 11:39:15.381 1959-1978/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb424bb40, error=EGL_SUCCESS
Take a look at this to get an idea how to do it:
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public Observable<List<RssItem>> getItems() {
return Observable.create(new Observable.OnSubscribe<List<RssItem>>() {
#Override
public void call(Subscriber<? super List<RssItem>> subscriber) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
subscriber.onNext(handler.getRssItemList());
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
reader.getItems()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<RssItem>>() {
#Override
public void call(List<RssItem> items) {
final ArrayList<TestItem> testItems = new ArrayList<>(items.size());
for (int size = items.size(), i = 0; i < size; i++) {
RssItem item = items.get(i);
testItems.add(new TestItem(item.getTitle(), item.getDescription()));
}
recyclerView.setAdapter(new TestItemAdapter(testItems));
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
});
}
try this
Observable.defer(() -> Observable.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
my app is throwing outofmemory exceptions to lots of people using it. my app creates a bitmap of the current screen then animates it to transition between pages.
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4222)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4217)
... 10 more
Caused by: android.view.InflateException: Binary XML file line #118: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:640)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:689)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.de_veloper.businessbuilder.MainActivity.premiumMenu(MainActivity.java:558)
... 13 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:614)
... 23 more
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 8683212 byte allocation with 6867876 free bytes and 6MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:726)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:547)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1014)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:3723)
at android.content.res.Resources.loadDrawable(Resources.java:3596)
at android.content.res.TypedArray.getDrawable(TypedArray.java:750)
at android.widget.ImageView.<init>(ImageView.java:151)
at android.widget.ImageView.<init>(ImageView.java:140)
at android.widget.ImageView.<init>(ImageView.java:136)
... 26 more
the code that creates the bitmap
public static Bitmap loadBitmapFromView(View v) {
Bitmap bitmap;
v.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v.getDrawingCache());
bitmap.setHasAlpha(false);
v.setDrawingCacheEnabled(false);
return bitmap;
}
the code that animates the bitmap
public void mainMenu(View view) {
$isonfirstpage = 0;
$isonmainmenu = 1;
$isonpremiummenu = 0;
final RelativeLayout backgroundLayout = (RelativeLayout) findViewById(R.id.activity_background);
LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout newLayout = (RelativeLayout)inflate.inflate(R.layout.main_menu, null);
Bitmap bitmap = loadBitmapFromView(backgroundLayout);
Drawable d = new BitmapDrawable(getResources(), bitmap);
backgroundLayout.removeAllViewsInLayout();
View mainmenuView = findViewById(R.id.mainmenuView);
View firstpageView = findViewById(R.id.firstpageView);
final ImageView screenie = new ImageView(getApplicationContext());
screenie.setImageDrawable(d);
backgroundLayout.addView(newLayout);
backgroundLayout.addView(screenie);
screenie.animate()
.translationY(backgroundLayout.getHeight())
.setDuration(300);
new Handler().postDelayed(new Runnable() {
public void run() {
backgroundLayout.removeView(screenie);
}
}, 1500);
}
when ever the Bitmap size is huse then you will get OutOfMemory Exception you can decode/scale the bitmap when ever you are setting it to the imageview.
public Bitmap decodeUri(Uri path) throws FileNotFoundException
{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o);
int REQUIRED_SIZE = 100;
int width_temp = o.outWidth;
int height_temp = o.outHeight;
int scale = 1;
while (true)
{
if(width_temp/2 < REQUIRED_SIZE || height_temp/2<REQUIRED_SIZE)
{
break;
}
width_temp/=2;
height_temp/=2;
scale*=2;
}
BitmapFactory.Options o1 =new BitmapFactory.Options();
o1.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(path),null,o1);
}
you can covert your image path to Uri as follows
decodeUri(Uri.fromFile(new File("your file path")))
I am trying to check if my application is launched for the first time. If yes, the user is asked for an input. Then, check if Wi-Fi is connected. If Wi-Fi is connected, I use the input provides by the user to load a WebView.
But, the app crashes on launch with an error
Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
Code
public class MainActivity extends Activity {
ProgressBar progressbar;
WebView webView;
LayoutInflater li = LayoutInflater.from(getBaseContext());
View promptsView = li.inflate(R.layout.propmt, null);
String URL;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
otherWork(promptsView);
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.loadUrl(URL);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
progressbar=(ProgressBar)findViewById(R.id.progressBar);
webView.setWebChromeClient(new WebChromeClient() {
// this will be called on page loading progress
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
//loadingTitle.setProgress(newProgress);
// hide the progress bar if the loading is complete
if (newProgress == 100) {
progressbar.setVisibility(View.GONE);
} else{
progressbar.setVisibility(View.VISIBLE);
}
}
});
} else {
AlertDialog.Builder AD = new AlertDialog.Builder(this);
AD.setIcon(R.drawable.ic_launcher);
AD.setTitle("Not Connected To Wi-Fi/WLAN");
AD.setMessage("You need an Active Wi-Fi/WLAN on Alliance Broadband Network");
AD.setPositiveButton(android.R.string.ok, new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AD.show();
}
}
public void otherWork(View promptsView) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
//result.setText(userInput.getText());
SharedPreferences pos;
String fileName = "file";
pos = getSharedPreferences(fileName, 0);
SharedPreferences.Editor editor = pos.edit();
editor.putString("pwd", userInput.getText().toString());
editor.commit();
pos = getSharedPreferences(fileName, 0);
String data = pos.getString("pwd", "");
URL = data.toString();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
finish();
}
return super.onKeyDown(keyCode, event);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}<br>
LogCat
05-24 01:11:19.279: E/AndroidRuntime(3719): FATAL EXCEPTION: main
05-24 01:11:19.279: E/AndroidRuntime(3719): Process: com.mavenmaverick.ipconnect, PID: 3719
05-24 01:11:19.279: E/AndroidRuntime(3719): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mavenmaverick.ipconnect/com.mavenmaverick.ipconnect.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread.access$800(ActivityThread.java:144)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.os.Handler.dispatchMessage(Handler.java:102)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.os.Looper.loop(Looper.java:135)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread.main(ActivityThread.java:5221)
05-24 01:11:19.279: E/AndroidRuntime(3719): at java.lang.reflect.Method.invoke(Native Method)
05-24 01:11:19.279: E/AndroidRuntime(3719): at java.lang.reflect.Method.invoke(Method.java:372)
05-24 01:11:19.279: E/AndroidRuntime(3719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
05-24 01:11:19.279: E/AndroidRuntime(3719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 01:11:19.279: E/AndroidRuntime(3719): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.view.LayoutInflater.from(LayoutInflater.java:219)
05-24 01:11:19.279: E/AndroidRuntime(3719): at com.mavenmaverick.ipconnect.MainActivity.<init>(MainActivity.java:47)
05-24 01:11:19.279: E/AndroidRuntime(3719): at java.lang.reflect.Constructor.newInstance(Native Method)
05-24 01:11:19.279: E/AndroidRuntime(3719): at java.lang.Class.newInstance(Class.java:1572)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
05-24 01:11:19.279: E/AndroidRuntime(3719): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
05-24 01:11:19.279: E/AndroidRuntime(3719): ... 10 more
LayoutInflater li = LayoutInflater.from(getBaseContext());
First, you do not need getBaseContext(), nor do you need LayoutInflater.from(). Use getLayoutInflater().
Second, you cannot call methods on the Activity superclass until after super.onCreate(), except in certain situations. Please postpone your initialization of promptsView until after super.onCreate() has been called.
View view = inflater.inflate(R.layout.fragment_name, container, false);
view.getContext();
Use view.getContext() wherever you need Application Context in fragments.