I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need
Related
I want to pass my API response to another activity . I am using intent but getting null in the next activity .
My code is MainPage.java
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
}
I am getting the correct response .
Calculation.java
Intent intn = new Intent();
members = intn.getStringExtra("MEMBERS");
System.out.println("dmkmdk"+members);
//no_of_members = Integer.parseInt(members);
I also want to parse it in integer form .
you should get extra like this, don't initiate an intent object
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("MEMBERS");
Try to save data in SharedPreference instead Intent.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("MEMBERS",members);
editor.apply();
For retriving data:-
editor.getString("MEMBERS", null); // getting String
Please try this
To Transfer data in next activity
public void onResponse(String response) {
System.out.println("output -- "+response);
members = response;
Intent intn = new Intent(MainPage.this,Calculation.class);
intn.putExtra("MEMBERS",members);
startActivity(intn)
}
In New activity where you want to get data try this line
String resFromLast = getIntent().getExtras().getString("MEMBERS");
Log.e("Response From last activity is :" ,resFromLast);
MEMBERS is that key you passed in last activity with intent.
Hope it works.
This is my Activity 1
final Intent ridesameIntent = new Intent(this, Activity2.class);
TextView userText = (TextView) findViewById(R.id.username);
ImageView userImage = (ImageView) findViewById(R.id.profile_pic);
String userNameMessage = userText.getText().toString();
String userPicMessage = userImage.toString();
ridesameIntent.putExtra(EXTRA_MESSAGE_USERNAME,userNameMessage);
ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC,userPicMessage);
startActivity(ridesameIntent);
This is Activity 2
Intent userDetail = getIntent();
String userPicMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERPIC);
String userNameMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERNAME);
TextView userdetail1 = (TextView) findViewById(R.id.username_scroll);
ImageView userdetail2 = (ImageView) findViewById(R.id.profile_pic_scroll);
userdetail1.setText(userNameMessage);
userdetail2.setImageURI(Uri.parse(userPicMessage));
I have tried passing the uri but getting no results in passing the user pic
also for help here is the code which fetches user profile from Facebook and sets it into the navbar of Activity 1
public void setUserProfile(String jsondata) {
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e) {
e.printStackTrace();
}
}
So please suggest me how can i get the image to activity 2.
Hello this is my code by which i get rid of this problem
In first Activity
Profile profile = Profile.getCurrentProfile();
Bundle mBundle = new Bundle();
mBundle.putParcelable("pic", profile);
Intent loginint = new Intent(MainActivity.this,DashBoard.class);
loginint.putExtra("email",email);
loginint.putExtras(mBundle);
startActivity(loginint);
finish();
And in Second Activity where u want to show that Image
Intent intent = getIntent();
Bundle mBundle =intent.getExtras();
Profile profile;
if (mBundle != null) {
profile = (Profile) mBundle.getParcelable("pic");
} else {
profile = Profile.getCurrentProfile();
}
Picasso.with(DashBoard.this)
.load(profile.getProfilePictureUri(400, 400).toString())
.into(mfbimage);
here mfbimage is object of ImageView where u want to show that Profile Picture.
profile_pic_url.getString("url") extract this value into a variable and pass it as your intent extra and then load it with a Picasso in your second activity like in your setUserProfile method.
EDIT.
So in your setUserProfile(String jsondata) method on this line Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture); in your load() method you're extracting an url string from a JSONObject by calling profile_pic_url.getString("url"). You can create a field from that statement via Right click -> Refactor -> Extract -> Field... And then call put it as extra to your intent by calling ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC, fieldNameThatYouExtracted);
Then in your second activity call
Picasso.with(this).load(userPicMessage).into(userPicMessage); instead of userdetail2.setImageURI(Uri.parse(userPicMessage));
After that you can learn how to simplify json deserialization using GSON library Leveraging the Gson Library
You can pass the image Bitmap through the intent to the second activity as it implements the Parcelable interface.
Bitmap profileBitmap = ((BitmapDrawable)user_picture.getDrawable()).getBitmap();
ridesameIntent.putExtra("profilePic", profileBitmap);
And on the other end :
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("profilePic");
For storing the serilaizable java object i m using below code
if(sharedpreferences.getString(ComplexObjectXMl,"")!=null) {
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject .class, sharedpreferences.getString(ComplexObjectXMl,""));
} catch (Exception e) {
e.printStackTrace();
}
Intent i1 = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i1);
}
new MyAsyncTask().execute();
In MyAsyncTask i m storing the XmlDataOverHttp in sharedPreferences. Will it get updated everytime if i like do this
you can compare byte array of those object. one coming from shared preference and other which is latest.
byte[] array = new Gson().toJson(latestObject).getBytes(); //your lattest byte array
byte[] secondArray = new Gson().toJson(objectConvertedFromSharedPreferenceOLD).getBytes();
if (Arrays.equals(array, secondArray))
System.out.println("They are same");
else
System.out.println("Nope...");
and as you said you can use service or shared preference to check hourly update in oncreateView() but it only happens when user open your app(between hour it will call api for list items)
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
long lastUpdateTime = mSettings.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (3600000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
SharedPreferences.Editor editor = mSettings.edit();
lastUpdateTime = System.currentTimeMillis();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Start Update for listview your URL to fetch data and then you can check and compare object
also you can use swipeRefreshLayout so user can also refresh data*/
//asyncRequestTime.execute(URL);
}
i'm having some trouble working with there checkbox. So in my app the user as 2 check boxes, and then a button, that button opens a new intent, and i need to pass the information through the intent to know if the checkbox is checked or not. I'm passing that information with the .putExtra() but then in the new intent when i do a if statement my app always crashes here because it gives me always a null pointer exception.
Here's the code for the button and pass the information:
final CheckBox sabado = (CheckBox) findViewById(R.id.checkBoxSabado);
final CheckBox domingo = (CheckBox) findViewById(R.id.checkBoxDomingo);
//Clique no botao "PROCURAR"
buttonProcurar.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick(View v) {
if(deTextPartida.getText().toString().equals(paraTextDestino.getText().toString())){
Toast.makeText(getBaseContext(), "Partida e destino nao podem ser iguais, escolha de novo!", Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(horariosMenu.this, mostraHorario.class);
i.putExtra("Partida", deTextPartida.getText().toString());
i.putExtra("Destino", paraTextDestino.getText().toString());
i.putExtra("Sabado", sabado.isChecked());
i.putExtra("Domingo", domingo.isChecked());
startActivity(i);
}
}
}
);
And here's the code to get it:
Bundle data = getIntent().getExtras();
if(data == null){
return;
}
String Partida = data.getString("Partida");
String Destino = data.getString("Destino");
String Sabado = data.getString("Sabado");
String Domingo = data.getString("Domingo");
if(Sabado.equals("true")){
Toast.makeText(getBaseContext(), Sabado, Toast.LENGTH_LONG).show();
}
What am i doing wrong guys ? :X
In "sabado" y "domingo" you are sending boolean values through putExtra method. Then in the Activity that receive the data, you assign a String value. You can write some like:
i.putExtra("Sabado", sabado.isChecked()+"");
i.putExtra("Domingo", domingo.isChecked()+"");
And then:
String Sabado = data.getString("Sabado");
String Domingo = data.getString("Domingo");
So ended up solving my problem. I'll post here so if in the future there are some with the same problem they can check right here.
I just changed my bundle, i found a way to get the Extras information another way :
Intent intent = getIntent();
String Partida = intent.getStringExtra("Partida");
String Destino = intent.getStringExtra("Destino");
boolean Sabado = intent.getBooleanExtra("Sabado", true);
boolean Domingo = intent.getBooleanExtra("Domingo", true);
And in the if statement (the one causing problem) i just had to do:
if(Sabado){
Toast.makeText(getBaseContext(), Sabado, Toast.LENGTH_LONG).show();
}
Because now "Sabado" is a boolean, and so in if(Sabado) i check if he is true or false, wich is the value of if the checkbox is checked or not.
So that's it guys, hope it helps
I'm looking at making a change in an app I'm working on (it's based off of this: http://goo.gl/rDBXVl) from loading a cloud based resource to a local based resource. I'm not particularly sure how I would go about doing this. I want to go from pulling a JSON file off the internet to pulling the JSON from my Assets folder.
I located the area in the app where it pulls the URL and loads the JSON but am unsure of what changes to make at this point.
public void loadData (Bundle savedInstanceState) {
// Check Network State
if (!NetworkUtil.getNetworkState(this)) {
final RetryFragment fragment = RetryFragment.getFragmentWithMessage("No connection");
this.addFragment(fragment, RetryFragment.TAG, true);
return;
}
if (savedInstanceState == null || savedInstanceState.get(KEY_LIST_DATA) == null) {
final String url = super.getResources().getString(R.string.config_wallpaper_manifest_url);
if (url != null && URLUtil.isValidUrl(url)) {
// Add Loading Fragment
final LoadingFragment fragment = new LoadingFragment();
this.addFragment(fragment, LoadingFragment.TAG, true);
// Load Data
final RestClientHandler handler = new RestClientHandler(this);
RestClient.get(this, url, handler);
}
} else {
Log.i(TAG, "Restored Instance");
this.mData = (ArrayList<NodeCategory>) savedInstanceState.get(KEY_LIST_DATA);
this.mPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
if (this.mPosition != -1) {
mIgnoreSelection = true;
}
this.configureActionBar();
}
}
You have another option,
just save json in sharedpreferences. so easily read and write it.
Save sharedpreferences code bellow.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}