I have a usual Intent from one activity to an other and give the second activity the path to the file needed.
Activity one:
private void onFileClick(int position)
{
File file =new File(folder+ "/"+ getListAdapter().getItem(position).toString());
Intent i = new Intent(this, (Activity two).class);
Log.e("Given File",file.toString());
i.putExtra(file.toString(), key);
startActivity(i);
}
Activity two:
#Override
protected void onCreate(Bundle savedInstanceState)
{
Intent i = getIntent();
String filepath = i.getStringExtra((Activity One).key); //Returns null
File parseFile = new File(filepath); //NullpointerExeption
}
Have i initialized the intent wrong?
Related
I was working on a simple phone app that shows the Call log and contacts also offers the possibility to call someone " It's Simply A Phone Caller ".
The problem is when I was trying to retrieve the call log list using the cursor I got an error (Redline) that says the value must be >= 0.
Here is my fragment code
public class CallLogFragment extends Fragment {
private RecyclerView recyclerView;
private ArrayList<ModelCalls> arrayList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.call_log_fragment, container, false);
recyclerView = view.findViewById(R.id.call_log_rv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
CallLogAdapter adapter = new CallLogAdapter(getContext(), getCallLog());
recyclerView.setAdapter(adapter);
return view;
}
private ArrayList<ModelCalls> getCallLog() {
Cursor cursor = getContext().getContentResolver().query(
CallLog.Calls.CONTENT_URI,
null,
null,
null,
CallLog.Calls.DATE + " ASC"
);
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String duration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
cursor.moveToFirst();
while (cursor.moveToNext()) {
ModelCalls modelCalls = new ModelCalls(date, number, duration, name);
arrayList.add(modelCalls);
}
return arrayList;
}
}
And This is MainActivity Code :
public class MainActivity extends AppCompatActivity {
private String[] PERMISSIONS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PERMISSIONS = new String[]{
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.WRITE_CALL_LOG
};
if (!EasyPermissions.hasPermissions(this, PERMISSIONS)){
EasyPermissions.requestPermissions(this,
"Please allow Phone to access all the permissions",
123,
PERMISSIONS);
}
MaterialToolbar toolbar = findViewById(R.id.toolbar);
BottomNavigationView navigationView = findViewById(R.id.bottom_nav_view);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Phone");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new CallLogFragment()).commit();
navigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment selectedFragment = null;
switch (id){
case R.id.nav_phone:
selectedFragment = new CallLogFragment();
getSupportActionBar().setTitle("Phone");
break;
case R.id.nav_contacts:
selectedFragment = new ContactsFragment();
getSupportActionBar().setTitle("Contacts");
break;
case R.id.nav_favorites:
selectedFragment = new FavoritesFragment();
getSupportActionBar().setTitle("Favorites");
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
}
and I added those permissions to the manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
And Here is my error when running the app :
2021-09-20 16:13:32.725 10584-10584/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.highui.myphone, PID: 10584
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1285
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:515)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:138)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:52)
at android.database.CursorWrapper.getString(CursorWrapper.java:141)
at com.highui.myphone.CallLogFragment.getCallLog(CallLogFragment.java:50)
at com.highui.myphone.CallLogFragment.onCreateView(CallLogFragment.java:36)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1440)
at android.app.Activity.performStart(Activity.java:8109)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3806)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:235)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:215)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:187)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:105)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
you are trying to get information from outside the loop and also there is no specific projection for cursor.
Add projection in cursor and fetch information from cursor inside while loop.
like below code
private ArrayList<ModelCalls> getCallLog() {
String[] projection = new String[]{
CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER,
CallLog.Calls.DURATION,
CallLog.Calls.DATE
};
Cursor cursor = getContext().getContentResolver().query(
CallLog.Calls.CONTENT_URI,
projection,
null,
null,
CallLog.Calls.DATE + " ASC"
);
cursor.moveToFirst();
while (cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String duration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
ModelCalls modelCalls = new ModelCalls(date, number, duration, name);
arrayList.add(modelCalls);
}
cursor.close();
return arrayList;
}
Good day,
I have an array adapter in Activity1 in my AndroidStudio project. I would like to transfer two specific items from the ArrayAdapter (in positions 1 and 2) to Activity2 with an intent. (the ArrayAdapter is connected to an editTextNumber) That works well if I then display the two items in a TextView. But if I want to convert the items to an int, the app always crashes. I can somehow just convert "message1" into an int. Why is that so?
Thank you for your help
(Activity 1):
[...]
#Override
protected void onCreate(Bundle savedInstanceState) {
ArrayAdapter adapterzeit = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, zeit1);
Intent intent = new Intent(this, Activity2.class);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent.putExtra("EXTRA_MESSAGE1", adapterzeit.getItem(1).toString());
intent.putExtra("EXTRA_MESSAGE2", adapterzeit.getItem(3).toString());
startActivity(intent);
}
});
}
(Activity 2):
[...]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
Intent intent = getIntent();
String message1 = intent.getStringExtra("EXTRA_MESSAGE1");
String message2 = intent.getStringExtra("EXTRA_MESSAGE2");
int numberInt = Integer.parseInt(message1);
int number2 = Integer.parseInt(message2);
}
}
You add the extra to the Intent like this:
intent.putExtra("EXTRA_MESSAGE1", adapterzeit.getItem(1).toString());
and then you try to extract it from the Intent like this:
String message1 = intent.getStringExtra("EXTRA_MESSAGE");
You are using different String values for the keys! EXTRA_MESSAGE != EXTRA_MESSAGE1
This is one reason why you should always use constant definitions for these kinds of things, then you wouldn't have this problem. For example, in Activity1:
public static final String EXTRA_MESSAGE1 = "EXTRA_MESSAGE1";
intent.putExtra(EXTRA_MESSAGE1, adapterzeit.getItem(1).toString());
and then in Activity2:
String message1 = intent.getStringExtra(Activity1.EXTRA_MESSAGE1);
I'm loading an Image into an ImageView using a link, and I'm trying to pass this link from one activity to display on another activity by an Intent. However, the Image just seems to come up blank.
Below I have listed the code associated with the two activities, as well as the adapter of the RecyclerView that the information is being passed from in the first activity
ActivityOne.java
private ArrayList<String> mImageUrls = new ArrayList<>();
...
mImageUrls.add("https://data.oireachtas.ie/ie/oireachtas/member/id/Se%C3%A1n-Haughey.S.1987-04-25/image/large");
...
#Override
public void onNoteClick(int position) {
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra("EXTRA_KEY_NAME", mNames.get(position));
intent.putExtra("EXTRA_KEY_IMAGE", mImageUrls.get(position));
startActivity(intent);
}
ActivityTwo.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_members_map_detailed);
tvMemberName = findViewById(R.id.tvClareMemberNameDetailed);
tvMemberParty = findViewById(R.id.tvClareMemberPartyDetailed);
tvMemberConstituency = findViewById(R.id.tvClareMemberConstituencyDetailed);
tvMemberAddress = findViewById(R.id.tvClareMemberAddressDetailed);
tvMemberEmail = findViewById(R.id.tvClareMemberEmailDetailed);
tvMemberPhone = findViewById(R.id.tvClareMemberPhoneDetailed);
tvMemberContributions = findViewById(R.id.tvClareMemberContributionsDetailed);
imgMember = findViewById(R.id.imgClareMemberImageDetailed);
Intent intent = getIntent();
String mName = intent.getStringExtra("EXTRA_KEY_NAME");
String mParty = intent.getStringExtra("EXTRA_KEY_PARTY");
String mConstituency = intent.getStringExtra("EXTRA_KEY_CONSTITUENCY");
String mAddress = intent.getStringExtra("EXTRA_KEY_ADDRESS");
Uri myUri = Uri.parse(intent.getStringExtra("EXTRA_KEY_IMAGE"));
String mEmail = intent.getStringExtra("EXTRA_KEY_EMAIL");
String mPhone = intent.getStringExtra("EXTRA_KEY_PHONE");
String mContributions = intent.getStringExtra("EXTRA_KEY_CONTRIBUTIONS");
tvMemberName.setText(mName);
tvMemberParty.setText(mParty);
tvMemberConstituency.setText(mConstituency);
tvMemberAddress.setText(mAddress);
tvMemberEmail.setText(mEmail);
tvMemberPhone.setText(mPhone);
tvMemberContributions.setText(mContributions);
imgMember.setImageURI(myUri);
Adapter information associated with Image
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Glide.with(mContext)
.asBitmap()
.load(mImageUrls.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.party.setText(mParties.get(position));
When I click first or second item from 1st array list I get first item from array list two, but I need if i click second item on array list 1 I get shown second item from list two
public class SecondActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> 1stArrayList;
ArrayList<String> 2ndArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
listView = (ListView) findViewById(R.id.listView);
1stArrayList = new ArrayList<>();
1stArrayList .add("A");
1stArrayList .add("B");
1stArrayList .add("C");
2ndArrayList = new ArrayList<>();
2ndArrayList.add("1");
2ndArrayList.add("2");
2ndArrayList.add("3");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, 1stArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String 2ndArrayList= listView.getItemAtPosition(position).toString();
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList ", 2ndArrayList );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
}
}
A possible solution would be getting the value directly from the array using the position of the view clicked. Like the following:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String secListItem = secArrayList.get(position);
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList", secListItem );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
But you have to be sure that both the arrays will have the same size or you may have an IndexOutOfBoundsException.
Another solution would be using some Map with the values from arraylist1 and arraylist2, implementing a custom adapter that extends BaseAdapter, populating the views with the values from the first array with getView() and using getItem() to return the values from the second list, but that's harder to do.
Also if you don't mean to persist the item and only transfer them between activities, you can use the Intent to do it. In this way:
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
Intent.putExtra("2ndArrayList", secListItem);
startActivity(intent);
And recover in the third activity with something like:
String secArrayItem = "";
Bundle extras = getIntent().getExtras();
if (extras != null) secArrayItem = extras.getString("2ndArrayList");
I am trying to put a spinner while my data is loaded and UI updated so for this task I do this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_details);
setTitle("Details");
startButt = (Button)findViewById(R.id.BeginJourney);
Map = (Button)findViewById(R.id.map_btn1);
boolean GreenButtState = getIntent().getBooleanExtra("GreenButtState", false);
boolean FastButtonState = getIntent().getBooleanExtra("FastButtonState", false);
AsyncTask<Void, Void, Void> LoadingTask = new AsyncTask<Void, Void, Void>()
{
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Message");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
final HashMap<String, Object> trip1;
Intent intent = getIntent();
mXmlRpcUrl = intent.getStringExtra("XmlRpcUrl");
mSessionID = intent.getStringExtra("SessionID");
mGetSavedTripFunc = intent.getStringExtra("GetSavedTripFunc");
newTripID = intent.getIntExtra("newTripID", 0);
variantID = intent.getIntExtra("VariantID", 0);
Week = intent.getIntExtra("WeekState", 0);
CityName = intent.getStringExtra("NameOfCity");
Flag = intent.getIntExtra("Flag", 0);
startLatitude = intent.getDoubleExtra("startLatitude", 0.0);
startLongitude = intent.getDoubleExtra("startLongitude", 0.0);
endLatitude = intent.getDoubleExtra("endLatitude", 0.0);
endLongitude = intent.getDoubleExtra("endLongitude", 0.0);
trip1 = (HashMap<String, Object>) intent.getSerializableExtra("Variant");
variant = new Variant();
variant.Read(trip1);
startButt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(RoadDetails.this, Localisation.class);
intent.putExtra("SessionID", mSessionID);
intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
intent.putExtra("NewTripID", newTripID);
intent.putExtra("VariantID", variantID);
intent.putExtra("WeekState", Week);
intent.putExtra("NameOfCity", CityName);
intent.putExtra("Variant", (Serializable)trip1);
intent.putExtra("Flag", Flag);
intent.putExtra("startLatitude", startLatitude);
intent.putExtra("startLongitude", startLongitude);
intent.putExtra("endLatitude", endLatitude);
intent.putExtra("endLongitude",endLongitude);
startActivity(intent);
}
});
Map.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Intent intent1 = new Intent (RoadDetails.this, MapDraw.class);
Intent intent1 = new Intent (RoadDetails.this, OSMActivity.class);
intent1.putExtra("SessionID",mSessionID);
intent1.putExtra("endLatitude", endLatitude);
intent1.putExtra("endLongitude",endLongitude);
intent1.putExtra("startLatitude", startLatitude);
intent1.putExtra("startLongitude", startLongitude);
intent1.putExtra("Variant", (Serializable)trip1);
startActivity(intent1);
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
GettingData();
this.dialog.dismiss();
}
};
LoadingTask.execute((Void[])null);
}
However when I do this there is a delay before opening the the activity that contains this code (I want the spinner to be there while the data is loaded) the spinner is not showing. There is just a delay (for the data to be loaded - lets also call it screen freeze for a 1 - 3 seconds) and thats it. What am I doing wrong? I want the spinner to show while the data is loaded and after that to be dismissed. I also what to mention that in the method GettingData(); I am changing the UI - adding Layouts dynamically, adding images etc.
try this...this will work
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
this.dialog.setMessage("Message");
this.dialog.show();
//start your asynchronous task here
load your data here
//end asynchronous task
this.dialog.dismiss();
write ProgressDialog dialog; outside AsyncTask then
call
dialog = new ProgressDialog(RoadDetails.this);
dialog.setMessage("Message");
dialog.show();
inside onPreExecute().
Hope it will help you..