TextView does not show log - java

Okay I am new with android and i have been following a course but there are somethings that i don't understand.
This is LifeCycleT activity.
package com.example.killtheviolence.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class LifeCycleT extends Activity {
StringBuilder builde = new StringBuilder();
TextView textview;
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append( builde.toString() );
builde.append("\n");
textview.setText(builde.toString());
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText(builde.toString());
setContentView(textview);
}
protected void onResume() {
super.onResume();
log("resume");
}
protected void onPause() {
super.onPause();
log("paused");
if(isFinishing()) {
log("death");
}
}
}
Where this came from? From a ListView.
package com.example.killtheviolence.myapplication;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
String prueva[] = {"LifeCycleT","item2","item3","item4",
"item5 ", "item6 "};
public void onCreate(Bundle savedInstanceSate){
super.onCreate(savedInstanceSate);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, prueva));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String gate = prueva[position];
try {
Class<?> inst;
inst = Class.forName("com.example.killtheviolence.myapplication." + gate);
Intent intent = new Intent(this, inst);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
That's the main activity.
What I want to do show in the TextView the Log.d in the screen but I get an error:
Unable to resume activity
{com.example.killtheviolence.myapplication/com.example.killtheviolence.myapplication.LifeCycleT}:
java.lang.NullPointerException
So I looked for a reason (meaning for a NullPointerException and it was that
I used TextView before initializing on the line textview.setText(builde.toString());
What I did was create an instance of TextView in log function.
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append(builde.toString());
builde.append("\n");
TextView textview = new TextView(this);
textview.setText(builde.toString());
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText(builde.toString());
setContentView(textview);
}
Why have I to create two instances of TextView? And why have I to setText twice? Why doesn't it show anything in the TextView? (only shows when i wrote a "string" in the arguments of setText.)

fix your onCreate to set the field parameter not a local parameter:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
textview = new TextView(this); // << This used to be a local var, thats why NPE
textview.setText(builde.toString());
setContentView(textview);
}
Then remove the 2nd creation of the TextView from log
private void log(String text) {
Log.d("LifeCycleT", text);
builde.append("\n");
builde.append(text);
textview.setText(builde.toString());
}
Also notice that I changed your StringBuilder to append the text that you pass as a parameter into your log method

Related

Why does the Recycleview work differently when I start it or when I go back to it from an other activity?

I try to create a Shopping/ToDoList application where the items are contained in SharedPreferences.
When I start the application, and I choose what I want to execute, Shopping list part or ToDoList part, then the java code fetches the existing data from the SharedPreferences and give to the RecycleView to create and show a list.
It seems works totally correct, but if I push the "add" button, then a new Activity is executed where I can specify the items, and when I click the save button, then the java code safe to the SharedPreferences and close the Activity and goes back to the "list" activity where the list should appears again with the new item. But when one data is inserted not in order in SharedPreferences but between two older data then the list create method get crazy and repeat always only the last data from SharedPreferences. But when I close the application, and restart, or goes back to the Main activity where I can choose again which list part I want then the list is totally OK again.
That is the list creating java code:
package com.example.recycleviewapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ShoppingList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
private List<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ShoppingList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
StartDisplay();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
}
#Override
public void onItemClick(View view, int position) {
//sharedPreferences = getSharedPreferences("ShoppingList", Context.MODE_PRIVATE);
String item_click =adapter.getItem(position);
String[] itemarray = item_click.split(" ",0);
//Toast.makeText(this, adapter.RemoveItem(position), Toast.LENGTH_SHORT).show();
//adapter.RemoveItem(position);
//myEdit = sharedPreferences.edit();
myEdit.remove(itemarray[0]);
myEdit.commit();
adapter.notifyItemRemoved(position);
items.remove(item_click);
}
#Override
public void onClick(View v) {
Intent NewSLItem = new Intent(ShoppingList.this, NewSLItem.class);
startActivity(NewSLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
//sharedPreferences = getSharedPreferences("ShoppingList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
//Toast.makeText(this, entry.getKey(), Toast.LENGTH_SHORT).show();
String [] item_total = entry.getValue().toString().split(";");
items.add(entry.getKey() + " " + item_total[0] + " " + item_total[1]);
}
allEntries.clear();
}
}
Here is the code where I can specify the item:
package com.example.recycleviewapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class NewSLItem extends MainActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public List<String> list = new ArrayList<>();
public EditText etNewItem;
public String[] unit = {"liter", "kg", "pcs"};
public Spinner spinner;
public EditText amount;
public String itemName;
public TextView title;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist_popup);
sharedPreferences = getSharedPreferences("ShoppingList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = (Button)findViewById(R.id.addbtn);
title = findViewById(R.id.title);
etNewItem = (EditText) findViewById(R.id.etNewItem);
amount = (EditText) findViewById(R.id.amount);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,unit);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aa);
title.setText("Create a new item for ShoppingList");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
onAddItem();
finish();
}
});
}
public void onAddItem()
{
//myEdit = sharedPreferences.edit();
itemName = etNewItem.getText().toString();
String itemValue = amount.getText().toString() + ";" + spinner.getSelectedItem().toString();
myEdit.putString(itemName,itemValue);
myEdit.commit();
etNewItem.setText("");
}
}
and here is the RecyclerView code:
package com.example.recycleviewapp;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
if (meta_data.contains("High")) holder.myTextView.setBackgroundColor(Color.parseColor("#FF003B"));
holder.myTextView.setText(meta_data);
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
So the problem is in casef of only where the data is not in order in SharedPreferences and I go back from a new activity.
Please help me if you can, where should I fix my application?
Thanks in advance!!!
When you return to the list after adding an item, you reread all the items from the SharedPreferences in StartDisplay() (which is called from onResume(). This changes the data that the adapter is working with. However, you didn't tell the adapter that the data has changed. The adapter caches the Views and you must tell it when you modify the data, otherwise it doesn't know the data has changed. Add the following to StartDisplay() which will invalidate the adapter's cache and ensure that it rebuilds all the views:
adapter.notifyDataSetChanged()
Thank you for your help! It works.
But I noticed an other bug, what I would like to share.
The StartDisplay() function is earlier then where I define the adapter exactly so when I used the adapter.notifyDataSetChanged() then I got an exception as null object reference. So I put the function calling to the end of the initialization part and now everything is fine.

How to refresh RecyclerView in one fragment when data changed in another fragment

How do I refresh the data from a local database to RecyclerView when data was successfully submitted? I use the tabs on the application. 2nd-Tab functions to submit the data, and if successful, the data will be stored in localDB.
Data on localDB I will present at the 3rd-Tab.
But what happens, I have to swipe 1st-Tab, then swipe to the 2nd-Tab and then swipe to the new 3rd-Tab data on my localDB successfully displayed.
If the 2nd-Tab me to submit the data, then I swipe to 3rd-Tab, the data will not appear on the list of data.
How do I get the data directly displayed without the need to swipe to the first 1st-Tab and then to the 2nd-Tab and 3rd-Tab ???
MainActivity :
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.bertho.gmyl.fragments.EngagedFragment;
import com.bertho.gmyl.fragments.RequestFragment;
import com.bertho.gmyl.fragments.SigninFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.engine_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new SigninFragment(), "SIGN-IN");
adapter.addFrag(new EngagedFragment(), "ENGAGED ID");
adapter.addFrag(new RequestFragment(), "LOCATION");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
EngagedFragment (2nd-Tab) Form to save data
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bertho.gmyl.R;
import com.bertho.gmyl.model.Engaged;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.bertho.gmyl.realm.RealmHelper;
public class EngagedFragment extends Fragment implements View.OnClickListener {
private static final String TAG = EngagedFragment.class.getSimpleName();
private EditText nama, email, nohp;
private Button btnSaveConnection;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private RelativeLayout mRoot;
private View rootView;
private String userId;
private TextView lblNama, lblEmail, lblNohp;
private RelativeLayout relativeLayout;
private RealmHelper realmHelper;
public EngagedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_engaged, container, false);
realmHelper = new RealmHelper(getActivity());
String appName = getResources().getString(R.string.app_name);
loadLocalDB();
nama = (EditText) rootView.findViewById(R.id.txtName);
email = (EditText) rootView.findViewById(R.id.txtEmail);
nohp = (EditText) rootView.findViewById(R.id.txtNoHp);
lblNama = (TextView) rootView.findViewById(R.id.lblNameval);
lblEmail = (TextView) rootView.findViewById(R.id.lblEmailval);
lblNohp = (TextView) rootView.findViewById(R.id.lblNohpval);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.panelLabelDetail);
btnSaveConnection = (Button) rootView.findViewById(R.id.btnEngaged);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("tbl_engaged");
mFirebaseInstance.getReference("titleapp").setValue(appName);
mFirebaseInstance.getReference("titleapp").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "TITLE UPDATED FROM FIREBASE");
String appTitle = dataSnapshot.getValue(String.class);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, "FAILED TO READ TITLE FROM FIREBASE.", error.toException());
}
});
btnSaveConnection.setOnClickListener(this);
return rootView;
}
private void showSnack(String notify) {
mRoot = (RelativeLayout) rootView.findViewById(R.id.frag_engaged);
Snackbar snackbar = Snackbar.make(mRoot, notify, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void onClick(View v) {
if(v.getId() == R.id.btnEngaged) {
String txtName = nama.getText().toString();
String txtEmail = email.getText().toString();
String txtNo = nohp.getText().toString();
if(txtName.equals("") || txtName.isEmpty()) {
showSnack("Name must filled");
nama.requestFocus();
} else if (txtEmail.equals("") || txtEmail.isEmpty()) {
showSnack("Email must filled");
email.requestFocus();
} else if (txtNo.equals("") || txtNo.isEmpty()) {
showSnack("No.HP must filled");
nohp.requestFocus();
} else {
createUser(txtName, txtEmail, txtNo);
saveToLocalDB(txtName, txtEmail, txtNo);
}
}
}
private void saveToLocalDB(String txtName, String txtEmail, String txtNo) {
realmHelper.addEngaged(txtName, txtEmail, txtNo);
}
private void loadLocalDB() {
realmHelper.getAllData();
}
private void createUser(String name, String email, String nohp) {
userId = mFirebaseDatabase.push().getKey();
Engaged user = new Engaged(name, email, nohp);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
private void addUserChangeListener() {
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Engaged user = dataSnapshot.getValue(Engaged.class);
if (user == null) {
Log.e(TAG, "ENGAGED DATA IS NULL");
return;
}
Log.e(TAG, "ENGAGED DATA IS CHANGED!" + user.name + ", " + user.email);
lblNama.setText(user.name);
lblEmail.setText(user.email);
lblNohp.setText(user.nohp);
//relativeLayout.setVisibility(View.VISIBLE);
nama.setText("");
email.setText("");
nohp.setText("");
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "FAILED TO READ USER", error.toException());
}
});
}
}
RequestFragment (3rd-Tab) To display localDB
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bertho.gmyl.R;
import com.bertho.gmyl.adapter.AdapterEngaged;
import com.bertho.gmyl.model.ModelEngaged;
import com.bertho.gmyl.realm.RealmHelper;
import java.util.ArrayList;
public class RequestFragment extends Fragment {
private static final String TAG = "RequestFragment";
private RecyclerView recyclerView;
private View rootView;
private ArrayList<ModelEngaged> data;
private RealmHelper helper;
public RequestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_request, container, false);
data = new ArrayList<>();
helper = new RealmHelper(getActivity());
recyclerView = (RecyclerView) rootView.findViewById(R.id.rvArticle);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
setRecyclerView();
return rootView;
}
public void setRecyclerView() {
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
AdapterEngaged adapter = new AdapterEngaged(data, new AdapterEngaged.OnItemClickListener() {
#Override
public void onClick(ModelEngaged item) {
Toast.makeText(getContext(), "LIST CLICKED", Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
setRecyclerView();
}
}
Everything went smoothly, it's just that I hope the data can be displayed when the form is submitted and can be directly viewed on the 3rd-Tab
Try this,
Create an Interface in EngagedFragment
say,
public interface SubmitListener {
void onSubmit();
}
private SubmitListener onSubmitListener;
public void setSubmitListener(SubmitListener onSubmitListener){
this.onSubmitListener = onSubmitListener;
}
public SubmitListener getOnSubmitListener(){
return onSubmitListener;
}
In saveToLocalDB(...) method
call
onSubmitListener.onSubmit();
In MainActivity:
1) Update the below statement:
public class MainActivity extends AppCompatActivity implements EngagedFragment.SubmitListener
2) Make your ViewPagerAdapter adapter; variable as Global variable;
while adding fragment:
EngagedFragment engagedFrag = new EngagedFragment();
adapter.addFrag(engagedFrag, "ENGAGED ID");
...
viewPager.setAdapter(adapter);
3) add this after setting adapter
engagedFrag.setSubmitListener(this);
4) Override onSubmit() method and try the below code in that method
if(viewPager != null){
if(adapter != null){
Fragment fragment = adapter.getItem(2);
if(fragment != null){
RequestFragment requestFragment = (RequestFragment) fragment;
requestFragment.setRecyclerView();
}
}
}
try this
mViewPager.setOffscreenPageLimit(0);
if that doesnt help, please check below SO question:
fragment refresh On Swip
and about : mViewPager.setOffscreenPageLimit(0); this might not work as i found in one of #commonware 's answer's, the following :-
"Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1"

Get integer value from edittext And Access value on Button

I want to get int Value from Edittext and then access that value On Button. But When I Access On Button It Show Error Remove "Final" modifier of "val". When I remove it then on button listener mViewPager.setCurrentItem(val); Show error That Change modifier of 'val'to Final.
Here Is my Code
bt_Goto =(Button)findViewById(R.id.btn_goto);
bt_next =(Button)findViewById(R.id.btn_next);
bt_Prev =(Button)findViewById(R.id.btn_prev);
ed_text =(EditText)findViewById(R.id.editText1);
final int val=-1;
if(ed_text.getText().toString().length() > 0){
val = Integer.parseInt( ed_text.getText().toString() );
}
// String str = ed_text.getText().toString().trim();
mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
mViewPager.setCurrentItem(0);
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(val);
}
});
Full Code:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.app.Activity;
public class MainActivity extends Activity {
Button bt_next,bt_Prev,bt_Goto;
EditText ed_text;
ImageView iv;
ExtendedViewPager mViewPager;
AdView adView;
int val=-1;
private StartAppAd startAppAd = new StartAppAd(this);
private static final String AD_UNIT_ID = "ca-app-pub-3785804349839269/3077204438";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAppSDK.init(this, "101607288", "201235812", true);
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
bt_Goto =(Button)findViewById(R.id.btn_goto);
bt_next =(Button)findViewById(R.id.btn_next);
bt_Prev =(Button)findViewById(R.id.btn_prev);
ed_text =(EditText)findViewById(R.id.editText1);
if(ed_text.getText().toString().length() > 0){
val = Integer.parseInt( ed_text.getText().toString() );
}
// String str = ed_text.getText().toString().trim();
mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
mViewPager.setCurrentItem(0);
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(val);
}
});
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images =
{R.raw.a0002,R.raw.a0003,R.raw.a0004,R.raw.a0005,R.raw.a0006,R.raw.a0007,R.raw.a0008,R.raw.a0009,R.raw.a0010,
R.raw.a0011,R.raw.a0012,R.raw.a0013,R.raw.a0014,R.raw.a0015,R.raw.a0016,R.raw.a0017,R.raw.a0018,R.raw.a0019,R.raw.a0020,
R.raw.a0021,R.raw.a0022,R.raw.a0023,R.raw.a0024,R.raw.a0025,R.raw.a0026,R.raw.a0027,R.raw.a0028,R.raw.a0029,R.raw.a0030,
R.raw.a0031,R.raw.a0032,R.raw.a0033,R.raw.a0034,R.raw.a0035,R.raw.a0036,R.raw.a0037,R.raw.a0038,R.raw.a0039,R.raw.a0040,
R.raw.a0041,R.raw.a0042,R.raw.a0043,R.raw.a0044,R.raw.a0045,R.raw.a0046,R.raw.a0047,R.raw.a0048,R.raw.a0049,R.raw.a0050,
R.raw.a0051,R.raw.a0052,R.raw.a0053,R.raw.a0054,R.raw.a0055,R.raw.a0056,R.raw.a0057,R.raw.a0058,R.raw.a0059,R.raw.a0060,
R.raw.a0061,R.raw.a0062,R.raw.a0063,R.raw.a0064,R.raw.a0065,R.raw.a0066,R.raw.a0067,R.raw.a0068,R.raw.a0069,R.raw.a0070,
R.raw.a0071,R.raw.a0072,R.raw.a0073,R.raw.a0074,R.raw.a0075,R.raw.a0076,R.raw.a0077,R.raw.a0078,R.raw.a0079,R.raw.a0080,
R.raw.a0081,R.raw.a0082,R.raw.a0083,R.raw.a0084,R.raw.a0085,R.raw.a0086,R.raw.a0087,R.raw.a0088,R.raw.a0089,R.raw.a0090,
R.raw.a0091,R.raw.a0092,R.raw.a0093,R.raw.a0094,R.raw.a0095,R.raw.a0096,R.raw.a0097,R.raw.a0098,R.raw.a0099,R.raw.a0100,
R.raw.a0101,R.raw.a0102,R.raw.a0103,R.raw.a0104,R.raw.a0105,R.raw.a0106,R.raw.a0107,R.raw.a0108,R.raw.a0109,R.raw.a0110,
R.raw.a0111,R.raw.a0112,R.raw.a0113,R.raw.a0114,R.raw.a0115,R.raw.a0116,R.raw.a0117,R.raw.a0118,R.raw.a0119,R.raw.a0120,
R.raw.a0121,R.raw.a0122,R.raw.a0123,R.raw.a0124,R.raw.a0125,R.raw.a0126,R.raw.a0127,R.raw.a0128,R.raw.a0129,R.raw.a0130,
R.raw.a0131,R.raw.a0132,R.raw.a0133,R.raw.a0134,R.raw.a0135,R.raw.a0136,R.raw.a0137,R.raw.a0138,R.raw.a0139,R.raw.a0140,
R.raw.a0141,R.raw.a0142,R.raw.a0143,R.raw.a0144,R.raw.a0145,R.raw.a0146,R.raw.a0147,R.raw.a0148,R.raw.a0149,R.raw.a0150,
R.raw.a0151,R.raw.a0152,R.raw.a0153,R.raw.a0154,R.raw.a0155,R.raw.a0156,R.raw.a0157,R.raw.a0158,R.raw.a0159,R.raw.a0160,
R.raw.a0161,R.raw.a0162,R.raw.a0163,R.raw.a0164,R.raw.a0165,R.raw.a0166,R.raw.a0167,R.raw.a0168,R.raw.a0169,R.raw.a0170,
R.raw.a0171,R.raw.a0172,R.raw.a0173,R.raw.a0174,R.raw.a0175,R.raw.a0176,R.raw.a0177,R.raw.a0178,R.raw.a0179,R.raw.a0180,
R.raw.a0181,R.raw.a0182,R.raw.a0183,R.raw.a0184,R.raw.a0185,R.raw.a0186,R.raw.a0187,R.raw.a0188,R.raw.a0189,R.raw.a0190,
R.raw.a0191,R.raw.a0192,R.raw.a0193,R.raw.a0194,R.raw.a0195,R.raw.a0196,R.raw.a0197,R.raw.a0198,R.raw.a0199,R.raw.a0200,
R.raw.a0201,R.raw.a0202,R.raw.a0203,R.raw.a0204,R.raw.a0205,R.raw.a0206,R.raw.a0207,R.raw.a0208,R.raw.a0209,R.raw.a0210,
R.raw.a0211,R.raw.a0212,R.raw.a0213,R.raw.a0214,R.raw.a0215,R.raw.a0216,R.raw.a0217,R.raw.a0218,R.raw.a0219,R.raw.a0220,
R.raw.a0221,R.raw.a0222,R.raw.a0223,R.raw.a0224,R.raw.a0225,R.raw.a0226,R.raw.a0227,R.raw.a0228,R.raw.a0229,R.raw.a0230,
R.raw.a0231,R.raw.a0232,R.raw.a0233,R.raw.a0234,R.raw.a0235,R.raw.a0236,R.raw.a0237,R.raw.a0238,R.raw.a0239,R.raw.a0240,
R.raw.a0241,R.raw.a0242,R.raw.a0343,R.raw.a0344,R.raw.a0245,R.raw.a0246,R.raw.a0347,R.raw.a0248,R.raw.a0249,R.raw.a0250,
R.raw.a0251,R.raw.a0252,R.raw.a0253,R.raw.a0254,R.raw.a0255,R.raw.a0256,R.raw.a0257,R.raw.a0258,R.raw.a0259,R.raw.a0260,
R.raw.a0261,R.raw.a0262,R.raw.a0263,R.raw.a0264,R.raw.a0265,R.raw.a0266,R.raw.a0267,R.raw.a0268,R.raw.a0269,R.raw.a0270,
R.raw.a0271,R.raw.a0272,R.raw.a0273,R.raw.a0274,R.raw.a0275,R.raw.a0276,R.raw.a0277,R.raw.a0278,R.raw.a0279,R.raw.a0280,
R.raw.a0281,R.raw.a0282,R.raw.a0283,R.raw.a0284,R.raw.a0285,R.raw.a0286,R.raw.a0287,R.raw.a0288,R.raw.a0289,R.raw.a0290,
R.raw.a0291,R.raw.a0292,R.raw.a0293,R.raw.a0294,R.raw.a0295,R.raw.a0296,R.raw.a0297,R.raw.a0298,R.raw.a0299,R.raw.a0300,
R.raw.a0301,R.raw.a0302,R.raw.a0303,R.raw.a0304,R.raw.a0305,R.raw.a0306,R.raw.a0307,R.raw.a0308,R.raw.a0309,R.raw.a0310,
R.raw.a0311,R.raw.a0312,R.raw.a0313,R.raw.a0314,R.raw.a0315,R.raw.a0316,R.raw.a0317,R.raw.a0318,R.raw.a0319,R.raw.a0320,
R.raw.a0321,R.raw.a0322,R.raw.a0323,R.raw.a0324,R.raw.a0325,R.raw.a0326,R.raw.a0327,R.raw.a0328,R.raw.a0329,R.raw.a0330,
R.raw.a0331,R.raw.a0332,R.raw.a0333,R.raw.a0334,R.raw.a0335,R.raw.a0336,R.raw.a0337,R.raw.a0338,R.raw.a0339,R.raw.a0340,
R.raw.a0341,R.raw.a0342,R.raw.a0343,R.raw.a0344,R.raw.a0345,R.raw.a0346,R.raw.a0347,R.raw.a0348,R.raw.a0349,R.raw.a0350,
R.raw.a0351,R.raw.a0352,R.raw.a0353,R.raw.a0354,R.raw.a0355,R.raw.a0356,R.raw.a0357,R.raw.a0358,R.raw.a0359,R.raw.a0360,
R.raw.a0361,R.raw.a0362,R.raw.a0363,R.raw.a0364};
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
Declare the ed_text and mViewPager in your onCreate like this
final EditText ed_text =(EditText)findViewById(R.id.editText1);
final ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
and now you can access the ed_text value in the bt_Goto click listener like this
bt_Goto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed_text.getText().toString().length() > 0){
mViewPager.setCurrentItem(Integer.parseInt( ed_text.getText().toString()));
}
}
});
Remove the final keyword from your int
final int val=-1;
^^^^ remove that
Besides that, declare it as a class field so you can access it in the listener scope.
Declare your int val variable at class level
And when it come to method initialise it with -1.
Hope fully it ll work.
You can achieve this using temp variable.
int value_temp = -1;
if(ed_text.getText().toString().length() > 0){
value_temp = Integer.parseInt( ed_text.getText().toString() );
}
final int value = value_temp;
bt_Goto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(value);
}
});

Shared Preferences doesn't get updated

I'm trying to make a world creator thing like in games and I am using shared preferences to store the arrays and such. But there is a problem. I am trying to update it from another class so I use static variables to do so. But when I go back to the original class with the list view, I find out that nothing has been updated. Any ideas? Here is the code. Oh and no errors came in the logcat.
ListView class.
package you.don't.need-to-know;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
public static SharedPreferences prefs = null;
static String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("you.don't.need-to-know");
startActivity(openWorldNamer);
}
}
}
The Updater:
package you.don't.need-to-know;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
static String updater;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
worldNameEditor = (EditText) findViewById(R.id.editText1);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor editor = WorldMenu.prefs.edit();
editor.putString("worldString", updater);
editor.commit();
Intent openListWorld = new
Intent("you.don't.need.to-know");
startActivity(openListWorld);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Edit: New Code updated with closer to fixing. Updater and List Activity
Updater:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences
prefs, String key) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
Intent openListWorld = new
Intent("");
startActivity(openListWorld);
}});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
List Activity:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
It doesn't look like you are monitoring for changes in the shared preferences. see:
http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
So when you get that callback, it will tell you what key changed. Then you could update the adapter for your listview to have the new contents and call onDataSetChanged() in the adapter.
Alternatively, you could move your adapter setting code into the onResume() function. This would make it so when your activity resumes, you check the status of the shared preferences and set the adapter. Be warned though, if the user has scrolled down the list some distance and you call setAdapter() again in the resume, they will lose their scroll position.
EDIT:
Try:
Updater (this shouldn't need to start a new activity, this can just finish()):
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worldcreator);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
worldNameEditor = (EditText) findViewById(R.id.hello);
saver = (Button) findViewById(R.id.button1);
updater = worldNameEditor.getText().toString() + ",";
saver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = prefs.edit();
editor.putString("worldString", updater);
editor.commit();
finish();
}});
}
ListView:
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class WorldMenu extends ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// update your listview.
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
splitter = "Create World," + prefs.getString("worldString", "hello");
worldList = splitter.split(",");
setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
android.R.layout.simple_list_item_1, worldList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if(position == 0){
Intent openWorldNamer = new
Intent("");
startActivity(openWorldNamer);
}
}
}
Prefrences are defined at the activity level. I'll have my bounty please.
Call getActivity() to get the callers activity then use that to get the prefrences.
If you want structure send results back via interface. Implement the interface and use the interface to find the activity. Eclipse creates stubs for you.
Here is the complete class that just changes a prefrence save's it and immediately sends the result back to the calling class. It uses getActivity() so the two classes share the same prefrences. It calls back through an interface.
It's from my app com.gosylvester.bestrides
package com.gosylvester.bestrides;
import com.google.android.gms.maps.GoogleMap;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
//...
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
private int _mapType = -1;
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
public MapSettings() {
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
getDialog().setTitle(R.string.app_name);
View view = inflater.inflate(R.layout.activity_map_settings, container);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
// initialize to the shared preferences value
rg.clearCheck();
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
int x = sharedpref.getInt(MAP_TYPE, GoogleMap.MAP_TYPE_NORMAL);
RadioButton rb = null;
switch (x) {
case GoogleMap.MAP_TYPE_HYBRID:
rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_NORMAL:
rb = (RadioButton) view.findViewById(R.id.RDORoad);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
rb.setChecked(true);
break;
}
// set the listener after setting up
rg.setOnCheckedChangeListener(this);
return view;
}
public int getMapType() {
return _mapType;
}
public void setMapType(int mapType) {
this._mapType = mapType;
}
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
// save the settings
if (sharedpref == null) {
sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
}
sharedpref.edit().putInt(MAP_TYPE, mapType).commit();
}
}
/* here's a snipet of the other class */
public class KmlReader extends FragmentActivity implements
BestRidesSettingsDialogListener {
...
mMap.setMapType(sharedPref.getInt(
com.gosylvester.bestrides.MapSettings.MAP_TYPE,
GoogleMap.MAP_TYPE_NORMAL));
...
#Override
public void onMapSettingsChange(int mapType) {
// TODO Auto-generated method stub
if (mMap != null) {
mMap.setMapType(mapType);
}
}
Good Luck
Shared prefernces are meant to be used in multiple classes if all classes are in same process. You do not have to use static explicitely. Just use the same sharedprefernce in both classes.
when you go back to the original class it doesn't guarantee onCreate mothod of the original class can perform ,like other answers say ,you can put the code into onResume mothod ,or after startActivity(intent) add method finish() to finish current activity

Call layout from another class

Here I've called layout from another class and snippet as follows
class example extends Activity{
class2 btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn.color();
}
}
//Another class(class2)
public class class2 extends Activity{
protected void color(){
View inflatedView = getLayoutInflater().inflate(R.layout.main, null);
LinearLayout layoutcolor=(LinearLayout) inflatedView.findViewById(R.id.linearcolor);
//some code
}
}
How can I call layout id in class2 by that I can display it from class example above code floods error.
class example extends Activity {
class2 btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = new Class2();
btn.color(this);
}
}
// Another class(class2)
public class class2 {
protected void color(Activity mActivity) {
LinearLayout layoutcolor = (LinearLayout) mActivity.findViewById(R.id.linearcolor);
// some code
}
}
UPDATE: I created a sample and it works for me, just check your implementation. OR post full code.
package com.example.test;
import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class sampleMediaPlayer extends ListActivity {
// Toast mToast;
private TextView selection;
class2 btn;
private static final String[] items = { "Computer Hardware", "Featured", "Information Technology",
"Software", "Technical"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
items);
setListAdapter(adapter);
btn = new class2();
btn.color(this);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(items[position]);
}
// Another class(class2)
public class class2 {
protected void color(Activity mActivity) {
ListView layoutcolor = (ListView) mActivity.findViewById(android.R.id.list);
layoutcolor.setBackgroundColor(Color.GREEN);
Log.i("NIMISH", "HEy ");
}
}
}

Categories

Resources