FATAL EXCEPTION: main java.lang.RuntimeException: got asked about an unknown fragment - java

I have a view pager and 3 fragment .
my app work good with 2 of them but when i add the third fragment its return this error :
12-17 14:11:30.969: ERROR/AndroidRuntime(7350): FATAL EXCEPTION: main
java.lang.RuntimeException: got asked about an unknown fragment
a part of my code is like this :
if (position == 0) {
if (mContactList == null)
mContactList = new ContactListFragment();
return mContactList;
} else if (position == 1) {
if (mContact == null)
mContact= new ContactFragment(); // my third fragment
return mContact ;
} else {
int positionMod = position - 2;
mCursor.moveToPosition(positionMod);
long contactChatId = mCursor.getLong(ChatView.CONTACT_ID_COLUMN);
String contactName = mCursor.getString(ChatView.USERNAME_COLUMN);
long providerId = mCursor.getLong(ChatView.PROVIDER_COLUMN);
return ChatViewFragment.newInstance(contactChatId, contactName, providerId);
}

i think you are trying to refer other fragments from your current fragment.
Try to set setOffscreenPageLimit to 2. As stated in the docs :
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
Use this code :
ViewPager mViewPager = (ViewPager) findViewById(R.id.historypager);
mViewPager.setOffscreenPageLimit(2);

Related

how can i get to the main file directory on android 10 and 11

I have a problem like this and I could not find a solution. my problem is Now, besides the files I created in my application, I also need to access the files in the main directory. The code I use for this is as follows. When I press the back button it goes to the previous folder.
here is my code
public void DosyaGeri(View view) {
String yol = ((TextView) findViewById(
R.id.txtKmlDosyaKonumu)).getText().toString();
String android = "/storage/emulated/0/";
String atlama="/storage/emulated/0/Android/data/com.LiderBilgisayarYazilim.cepmap/files/";
// boolean defolt= yol == "/storage/emulated/0/";
if (File.separator.compareTo(yol) == File.separator.compareTo(android)) {
finish();
startActivity(new Intent(this, Harita.class));
return;
}
else if(File.separator.compareTo(yol) == File.separator.compareTo(atlama)){
yol = android;
DosyaListesiOlustur(yol);
}
else {
yol = yol.substring(0,
yol.substring(0, yol.length() - 2).lastIndexOf("/")) +
File.separator;
DosyaListesiOlustur(yol);
}
}
but this code does not work on xiaomi devices with android 10 or higher. The reason is that it uses a different directory instead of "storage / emulated / 0 /". and it gives access permission error to this directory. how can i solve this.

Slow background task and frequent crashing (App using NewsAPI)

I am working on a News app using newsapi. I have a homepage that downloads the top 15 articles and another page that has does the same but from the hackernews api. Each time I run the app from Android Studio, it shows a white screen for a few minutes before populating the list view.
I tried limiting the download rate, kept a check on the SQLite indexes and other things from StackOverflow but I can't seem to solve my issue.
When I go to the hackernews page and click on list, the app will just refresh itself and come back to the homepage
When running app from the emulator, it will either go to hackernews without loading homepage or just crash
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 when clicking last item in listview
App will only load 2 articles and give me a java.io.FileNotFoundException: https://www.summarizebot.com/api/summariz... error. This is because the URL from the API doesn't work (tested in the browser)
Homepage
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
...
//START THE BACKGROUND TASK
task = new BackgroundTask();
String s = task.execute("https://newsapi.org/v2/top-headlines?country=us&apiKey").get();
...
//POPULATE LIST WITH DATABASE CONTENT
updateContent();
public void updateContent(){
...
if(cursor.moveToFirst()){
homeStories.clear();
homeLinks.clear();
}
if(cursor.getCount() > 0) {
do {
homeStories.add(cursor.getString(nameIndex));
homeLinks.add(cursor.getString(addressIndex));
} while (cursor.moveToNext());
adapter.notifyDataSetChanged();
}
//BACKGROUND TASK
public class BackgroundTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground (String...urls){
//GET JSON AND SUMMARIES IN SINGLE FOR LOOP FOR EACH ARTICLE
...
for (int i = 0; i < 16; i++) {
JSONObject content = jsonArray.getJSONObject(i);
...
//ADD TO DATABASE
database.execSQL("INSERT INTO trending (name, address) VALUES ('" + title + "','" + address + "')");
//GET THE SUMMARY OF EACH ARTICLE
url = new URL("https://www.summarizebot.com/api/summarize?...
JSONArray j2Array = new JSONArray(s1);
for (int j = 0; j < j2Array.length(); j++) {
JSONObject object2 = j2Array.getJSONObject(j);
s2 += object2.getString("sentence");
}
//END OF MAIN FOR LOOP
}
Hackernews Page
//SAME AS ABOVE
After attempting to troubleshoot, I came up with a few questions:
How can I speed up background tasks for news articles?
How can I open an app and start background downloads without it crashing because of indexOutOfBounds?
How can I give download priority to the current activity instead of downloading everything at once?
How do I skip over broken links and continue getting the rest of the articles? App stops downloading at that point [FIXED: Surrounded InputStream with Try/Catch]

Firebase database pagination scrolling action

I'm following the tutorial:
https://codelabs.developers.google.com/codelabs/firebase-android/#6
I was trying to achieve pagination, Here is what i have modified:
...
Query query = databaseRef.limitToLast(50);
...
FirebaseRecyclerOptions<FriendlyMessage> options =
new FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(query, parser)
.build();
...
Here is the scrolling code as tutorial as default:
mFirebaseAdapter.registerAdapterDataObserver(new
RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
Now the screen shows only 50 messages.
But it don't scroll to the bottom when new messages coming.It works fine before using query.
I want to know where should I start to modified.
Thank you.
From the swift side:
By changing the startKey, we can query the data from where we want(from the end of the database) and achieve the pagination by scrolling to the top of the screen.
if (startKey == nil){
print("firebasetest_startkey: ",self.startKey)
// for first grabbing data operation
_refHandle = self.ref.child(channel_title).queryOrderedByKey().queryLimited(toLast: 30).observe(.value){(snapshot) in
guard let children = snapshot.children.allObjects.first as? DataSnapshot else{return}
if (snapshot.childrenCount > 0){
for child in snapshot.children.allObjects as! [DataSnapshot]{
if(!(self.messageKeys.contains((child as AnyObject).key))){
self.messages.append(child)
self.messageKeys.append(child.key)
self.itemTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
}
}
self.startKey = children.key
}
}
}else if (dragdirection == 0 && startKey != nil){
//going up
// for all other grabbing data operation from the bottom of the database
_refHandle = self.ref.child(channel_title).queryOrderedByKey().queryEnding(atValue: self.startKey).queryLimited(toLast: 10).observe(.value){(snapshot) in
guard let children = snapshot.children.allObjects.first as? DataSnapshot else{return}
if (snapshot.childrenCount > 0 ){
for child in snapshot.children.reversed(){
if ((child as AnyObject).key != self.startKey &&
!(self.messageKeys.contains((child as AnyObject).key))){
self.messages.insert(child as! DataSnapshot, at:0)
self.messageKeys.append((child as AnyObject).key)
self.itemTable.insertRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
}
}
self.startKey = children.key
}
}
}

Error when trying to get a bundle from another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
The part of the code where I try to retrieve and show the bundle is this:
Bundle bundlefrankrijk = getIntent().getExtras();
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");
TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);
SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);
if (scorefrankrijk > highScorefrankrijk) {
highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);
SharedPreferences.Editor editor = settingsfrankrijk.edit();
editor.putInt("HIGH_SCORE", scorefrankrijk);
editor.commit();
} else {
highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
}
This is how I'm sending the intent to the current activity:
Intent i = new Intent(QuizActivityFrankrijk.this,
QuizResultaatFrankrijk.class);
Bundle bundlefrankrijk = new Bundle(0);
bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
i.putExtras(bundlefrankrijk);
QuizActivityFrankrijk.this.finish();
startActivity(i);
Thanks in advance!
Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:
Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object
And when youre trying to:
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed
Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:
mIntent.putExtra("key", intValue)
and check that youre receiving it like this:
if (getIntent().getExtras() != null){
getIntent().getExtras().getInt("key");}
or just like this too:
if (getIntent().getExtras() != null){
getIntent().getExtras().get("key");}
Remember, if the key is just different in some character, it will return NULL.
Please read this for more info: https://developer.android.com/reference/android/content/Intent.html

Android - add table rows after table loading

I am reading UDP packets and i wanna display that info on UI as table in android app.
Here is my code,
try {
byte buffer[] = new byte[10000];<br/>
InetAddress address = InetAddress.getByName("192.168.xx.xx");<br/>
int port = xxx;<br/>
Log.d("..........","What will Happen ?? ");<br/>
for(int k=0;k<50;k++) { // 50 rows are added , This i wanna make it 5000+ rows so it takes plenty of time to load that table <br/>
DatagramPacket p = new DatagramPacket(buffer, buffer.length, address, port);<br/>
DatagramSocket ds = new DatagramSocket(port);<br/>
Log.d("..........","Perfect Binding .... Waiting for Data");<br/>
ds.receive(p);<br/>
Log.d("..........","Packet Received");<br/>
byte[] data = p.getData();<br/>
String result = "";<br/>
int b[] = new int[data.length];</br>
for (int i=0; i < 150; i++) {<br/>
result += Integer.toString( ( data[i] & 0xff ) + 0x100, 16).substring( 1 );<br/>
result += "_";<br/>
}<br/>
Log.d("Result => ",result); <br/>
TableLayout tl=(TableLayout)findViewById(R.id.TableLayout01);<br/>
TableRow tr=new TableRow(this);
TextView tv= new TextView(this);
TextView tv2 = new TextView(this);
tv.setPadding(5, 0, 5, 0);
tv2.setPadding(5,0,5,0);
String k1 = Integer.toString(k);
tv.setText(k1);
tv2.setText(it_version);
tr.addView(tv);
tr.addView(tv2);
tl.addView(tr,1);
ds.close();
}
} catch (Exception e) {
Log.e("UDP", "Client error", e);
}
If i keep 50 rows am able to display it properly without any time delay, if i put 3000 rows its taking too long time and sometimes app is hanging... I wanna add 50 entries to a table and load the table and again read 50 entries and append to the table without touching any button or anything so i have a table in UI and it will update automatically by reading UDP packets ... how i can achieve that ?? Any clue appreciated.
or once i read the UDP packet i wanna display it on UI[appending to the table],How i can do this ??[Scrolling and all i will take care] please let me know
I already tried using threads but no use
Basically, you need to implement an infinite listview. There are a couple strategies to do this:
You can get all the data and store it in a database and only show the user 50 at a time.
You can fetch only 50 at first and then fetch the next 50 when the user scrolls past them.
You can fetch 100, show 50 and then show next 50 when the user scrolls past the first 50. Pre-fetch the next 100 to show next and so on.
Once you figured out your fetching strategy, you need to implement the actual adapter and listview. Here's a good technique to do this. I would recommend that you don't re-invent the wheel and use this great library called EndlessAdapter unless you want to implement it for learning purposes.
Something like this is what you might use in order to get a infinite list effect when you don't have a cursor.
Please note this is a very rough draft since I deleted the code only relevant to my app, to help for you clarity, and for my privacy and the apps privacy. Also it may not be the best way of doing everything, but it worked the first time I wrote it (which took like 10 minutes) and worked beautifully for a very complex list, so I haven't bothered coming back to it.
class AsyncGetUpdates extends AsyncTask<Void, Void, List<UpdateDTO>>
{
#Override
protected void onPreExecute()
{
showDialog();
super.onPreExecute();
}
#Override
protected List<UpdateDTO> doInBackground(Void... params)
{
return APIHelper.getUpdates(count);
}
#Override
protected void onPostExecute(List<UpdateDTO> result)
{
killDialog();
isCurrentlyUpdating = false;
setAdapterData(result);
super.onPostExecute(result);
}
}
public void setAdapterData(List<UpdateDTO> result)
{
killDialog();
if (this != null && this.getActivity() != null)
{
Log.d(TAG, "setAdapterData");
if (lvUpdatesList.getAdapter() != null)
{
// save index and top position
int index = lvUpdatesList.getFirstVisiblePosition();
View v = lvUpdatesList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
lvUpdatesList.setSelectionFromTop(index, top);
}
else
{
updateListAdapter = new UpdateListAdapter(this.getActivity().getLayoutInflater(), result, this);
lvUpdatesList.setAdapter(updateListAdapter);
lvUpdatesList.refreshDrawableState();
}
}
// add in a listener to know when we get to the bottom
lvUpdatesList.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
// we do not want to update if we already are
if (isCurrentlyUpdating == false)
{
if (lvUpdatesList.getAdapter() != null && lvUpdatesList.getAdapter().getCount() == count)
{
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount)
{
isCurrentlyUpdating = true;
// add to the count of views we want loaded
count += 20;
// start a update task
new AsyncGetUpdates().execute();
}
}
}
}
});
}
Finally I would like to say that copy pasting might get you the results you want, but it will hinder you future ability. I would say study, read, learn, try, fail, and try again.

Categories