Android restore listview content - android

I have got two activities. In first you can input jobname and job place into inputtext views. First activity contains also navigation-draver menu (appearing from left side of screen). After clicking "Searc" button, results are shown in listview in second activity. You can long-click on any listview item and then it will be added to navigation-drawer in first activity. You can go back to first activity by clicking "back" arrow. The problem is, that when I will go back to first activity, press "Search" button again and then go back to first activity again, the navigation drawer menu is empty again (all items, which were added on first try are deleted). How to fix that?
Here is pic with my activities (sorry for poor quality):
1- first activity; 2- navigation drawer in first activity with added items from second activity' listview; 3- second activity (listview with search results)
EDIT:
My code from two activities (without imports to shorten it a little):
First (main):
public class MainActivity extends ActionBarActivity {
ListviewActivity lv = new ListviewActivity();
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
public ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ArrayList<String> arrayFav = new ArrayList<String>();
ArrayList<String> arrayLin = new ArrayList<String>();
private ImageView mImageViewLogo;
private Button mButtonSzukaj;
private EditText mEditTextPraca;
private EditText mEditTextMiejsce;
public static String nazwaStanowiska;
public static String nazwaMiejscowosci;
private Settings mSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mImageViewLogo = (ImageView)findViewById(R.id.imageViewLogo);
mButtonSzukaj = (Button) findViewById(R.id.buttonSzukaj);
mEditTextPraca = (EditText)findViewById(R.id.editTextPraca);
mEditTextMiejsce = (EditText)findViewById(R.id.editTextMiejsce);
final String mPrBefore = mEditTextPraca.getText().toString();
final String mPrAfter = mPrBefore.trim();
final String mMiBefore = mEditTextMiejsce.getText().toString();
final String mMiAfter = mMiBefore.trim();
mEditTextPraca.setText(mPrAfter);
mEditTextMiejsce.setText(mMiAfter);
mSettings = new Settings(this);
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
mDrawerList.setOnItemClickListener(null);
mDrawerList.setOnItemLongClickListener(null);
}
mAdapter.notifyDataSetChanged();
mButtonSzukaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(mEditTextPraca.getText().toString()) && (TextUtils.isEmpty(mEditTextMiejsce.getText().toString()))) {
mEditTextPraca.setError("Pole obowiązkowe!");
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextPraca.getText().toString())) {
mEditTextPraca.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextMiejsce.getText().toString())) {
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else {
nazwaStanowiska = mEditTextPraca.getText().toString();
nazwaMiejscowosci = mEditTextMiejsce.getText().toString();
Intent myIntent = new Intent(MainActivity.this, ListviewActivity.class);
MainActivity.this.startActivityForResult(myIntent, 1);
mSettings.setmText1(mEditTextPraca.getText().toString());
mSettings.setmText2(mEditTextMiejsce.getText().toString());
mSettings.save();
}
}
});
readPreferences();
}
protected void readPreferences(){
mEditTextPraca.setText(mSettings.getmText1());
mEditTextMiejsce.setText(mSettings.getmText2());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
ArrayList<String> passedText = data.getStringArrayListExtra("text");
ArrayList<String> passedLink = data.getStringArrayListExtra("link");
//arrayFav.clear();
//arrayLin.clear();
arrayFav.addAll(passedText);
arrayLin.addAll(passedLink);
addDrawerItems();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.podziel_sie_opinia) {
Intent mIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:661249888"));
mIntent.putExtra("sms_body", "Uważam, że aplikacja...");
startActivity(mIntent);
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void addDrawerItems() {
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayFav);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Tu pojawi się kliknięta oferta", Toast.LENGTH_LONG).show();
/*Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onet.pl"));
startActivity(myBrowserIntent);*/
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(arrayLin.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Usunięto z ulubionych!", Toast.LENGTH_SHORT).show();
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
}
mAdapter.notifyDataSetChanged();
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Twoje oferty");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
protected void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
and the second one (listview with results):
public class ListviewActivity extends ActionBarActivity {
int global_position =0;
boolean longClick = false;
static String wybranaOferta = "";
ArrayList<String> choosedOffer = new ArrayList<String>();
ArrayList<String> choosedLink = new ArrayList<String>();
MainActivity mainActiv;
static List<String> mLista = new ArrayList<>();
static ArrayList<String> positionArr = new ArrayList<String>();
static List<String> mListaTest1 = new ArrayList<>();
static List<String> mListaTest2 = new ArrayList<>();
static List<String> mListaLinki = new ArrayList<>();
static List<String> mListaNazwy = new ArrayList<>();
static List<String> mListaFirmy = new ArrayList<>();
private JobListAdapter mAdapter;
public Elements jobName, jobName2, jobNameComp, jobName2Comp;
private ProgressBar mProgress;
private Context context;
public ArrayList<String> workList = new ArrayList<String>();
public ArrayList<String> companyList = new ArrayList<String>();
public ArrayList<String> jobList = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private JazzyListView mListView;
public String doURLpraca = MainActivity.nazwaStanowiska;
public String doURLmiejsce = MainActivity.nazwaMiejscowosci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListView = (JazzyListView) findViewById(R.id.list);
mListView.setTransitionEffect(new FanEffect());
mListView.setItemsCanFocus(true);
//Progress bar
mListView.setEmptyView(findViewById(R.id.progressBarLoading));
Toast.makeText(getApplicationContext(), "Wyszukiwanie ofert...", Toast.LENGTH_LONG).show();
new NewThread().execute();
mAdapter = new JobListAdapter(this, jobList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mListaLinki.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
choosedOffer.add(mListaTest1.get(position).toString());
choosedLink.add(mListaLinki.get(position).toString());
Toast.makeText(getApplicationContext(), "Dodano do ulubionych!", Toast.LENGTH_SHORT).show();
return false;
}
});
}
protected void onPreExecute() {
}
public void onBackPressed() {
Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
intent.putStringArrayListExtra("text", choosedOffer);
intent.putStringArrayListExtra("link", choosedLink);
setResult(RESULT_OK, intent);
finish();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
String doURLwork = mainActiv.nazwaStanowiska;
String doURLplace = mainActiv.nazwaMiejscowosci;
Document doc, doc2;
Elements classs, lins;
String uerele;
try {
doc = (Document) Jsoup.connect("http://www.infopraca.pl/praca?q=" + doURLwork + "&lc=" + doURLplace)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
doc2 = (Document) Jsoup.connect("http://www.pracuj.pl/praca/" + doURLwork + ";kw/" + doURLplace + ";wp")
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
//Oferty
jobName = doc.select("h2.p-job-title a[href]"); //Infopraca
jobName2 = doc2.select("h2.offer__list_item_link a[href]"); //pracuj.pl
//Firmy
jobNameComp = doc.select("h3.p-name.company a[href]"); //Infopraca
jobName2Comp = doc2.select("h3.offer__list_item_link a[href]"); //pracuj.pl
//Oferty pracy
//Infopraca
mListaTest1.clear();
for (Element jobNames : jobName) {
mListaTest1.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2) {
mListaTest1.add(jobNames2.text() + "\n");
}
if(mListaTest1.size()==0){
Toast.makeText(getApplicationContext(), "Zmień parametry wyszukiwania!", Toast.LENGTH_LONG).show();
}
//--------------------------------------------------
//Firmy
//Infopraca
mListaTest2.clear();
for (Element jobNames : jobNameComp) {
mListaTest2.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2Comp) {
mListaTest2.add(jobNames2.text() + "\n");
}
//Linki do ofert
//Infopraca
for (Element link : jobName) {
mListaLinki.add(link.attr("abs:href"));
}
//Pracuj.pl
for (Element link : jobName2) {
mListaLinki.add(link.attr("abs:href"));
}
//Łączenie wyników - oferta + nazwa firmy
jobList.clear();
for(int i=0; i<mListaTest1.size(); i++){
jobList.add(mListaTest1.get(i)+"\n"+mListaTest2.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute(String result) {
}
#Override
protected void onPostExecute(String result) {
mAdapter.notifyDataSetChanged();
}
}
}

Generally, the first activity may be destroyed and recreated each time you go back to it. You might have to save list view items in activity's
onSaveInstanceState(Bundle)
method and load them again in onCreate. A simple example can be found in the first answer here
Or, you can just use fragments instead of two activities.
EDIT:
It seems like onSaveInstanceState only works when the activity is being closed by force, and it's philosophy is that onDestroy() method is not a safe place to save your data since it might not get called for various reasons.
The easiest way to do this is to use fragments instead of separate activities. The list adapter should be a member of activity and instead of opening a new activity, a fragment transaction would take place.
Using the back stack of fragment manager, the back button navigation will also be no problem and it would return the app to its initial state. Since the list is a field of the activity it can be easily shared between the fragments and it would not change due to fragment transactions.

Related

Navigation Drawer does not respond on touch

I am writing an app, where I am combining activivties and navigation drawer, which I have never tried before. Here is the problem: when I am trying to access menu elements by clicking from MainActivity, everything works perfect and clicked elements pass on to other activities. But when I am trying to access drawer from EventActivity, which is opened with one of the fields of the drawer, it just does not respond and closes. This happens whatever field I am trying to press on drawer from EventActivity. Here is the code of both
MainActivity:
public class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
MenuItem event,remind,setting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if(item.getItemId()==R.id.nav_events){
Intent intentEv=new Intent(MainActivity.this,EventActivity.class);
startActivity(intentEv);
}
else if(item.getItemId()==R.id.nav_reminders){
Intent intentRem=new Intent(MainActivity.this,RemindersActivity.class);
startActivity(intentRem);
}
else if(item.getItemId()==R.id.nav_settings){
Intent intentSet=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(intentSet);
}
return super.onOptionsItemSelected(item);
}
}
EventActivity
public class EventActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
MenuItem event,remind,setting;
FloatingActionButton fab;
FragmentManager fm;
OpenHelper openHelper;
SQLiteDatabase db;
ArrayList<ObjectItem> maps;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
fab=findViewById(R.id.fab);
list=findViewById(R.id.list);
openHelper=new OpenHelper(getBaseContext());
db=openHelper.getReadableDatabase();
listItem=new ArrayList<>();
viewData();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected= (String) list.getItemAtPosition(position);
//Убрать элемент
String desc = null,time = null,date=null;
Cursor csr=db.rawQuery("SELECT description FROM event WHERE header =\"" +selected + "\";",null);
if(csr!=null)
if(csr.moveToFirst())
desc=csr.getString(0);
Cursor csr2=db.rawQuery("SELECT time FROM event WHERE header = \"" +selected + "\";",null);
if(csr2!=null)
if(csr2.moveToFirst())
time=csr2.getString(0);
Cursor csr3=db.rawQuery("SELECT date FROM event WHERE header = \"" +selected + "\";",null);
if(csr3!=null)
if(csr3.moveToFirst())
date=csr3.getString(0);
Dialog dialog = new Dialog(EventActivity.this);
dialog.setContentView(R.layout.itemdialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
TextView textHeader = dialog.findViewById(R.id.ItemHeader);
textHeader.setText(selected);
TextView textDesc = dialog.findViewById(R.id.ItemDesc);
textDesc.setText(desc);
TextView textTime = dialog.findViewById(R.id.ItemTime);
textTime.setText(time);
TextView textDate = dialog.findViewById(R.id.ItemDate);
textDate.setText(date);
ImageButton imageButton=dialog.findViewById(R.id.imgBut);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openHelper.deleteData(selected);
maps.clear();
viewData();
dialog.dismiss();
}
});
dialog.show();
}
});
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
fm=getSupportFragmentManager();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(EventActivity.this,EventBuilderActivity.class);
startActivity(intent);
}
});
}
private void viewData() {
list.setAdapter(null);
Cursor cursor=openHelper.viewData();
maps = new ArrayList<ObjectItem>();
if(cursor.getCount()==0){
Toast.makeText(this,"No info",Toast.LENGTH_SHORT).show();
} else{
while (cursor.moveToNext()){
maps.add(new ObjectItem(cursor.getString(1),
cursor.getString(2),
cursor.getString(3),cursor.getString(4)));
}
adapter=new MeinAdapter(this, maps);
list.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if(item.getItemId()==R.id.nav_events){
Intent intentMain=new Intent(EventActivity.this,MainActivity.class);
startActivity(intentMain);
}
else if(item.getItemId()==R.id.nav_reminders){
Intent intentRem=new Intent(EventActivity.this,RemindersActivity.class);
startActivity(intentRem);
}
else if(item.getItemId()==R.id.nav_settings){
Intent intentSet=new Intent(EventActivity.this,SettingsActivity.class);
startActivity(intentSet);
}
return super.onOptionsItemSelected(item);
}
}

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

out of memory in MainActivity

Our application android use a lot of memory in MainActivity ( 32MB )
we don't know how to detect and specify where is exactly the problem
we try to comment all the code in MainActivity but No solution
Can someone help us to detect where the solution exactly in our Code ?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> CodeBar = new ArrayList<>();
private ArrayList<Integer> id_Four = new ArrayList<>() ;
private ArrayList<String> nomProd = new ArrayList<>() ;
private ArrayList<String> prix = new ArrayList<>() ;
private ArrayList<String> nomFour = new ArrayList<>() ;
private ArrayList<String> adresse = new ArrayList<>() ;
private ArrayList<String> tel = new ArrayList<>() ;
private ArrayList<String> description = new ArrayList<>() ;
private ArrayList<Float> ratings = new ArrayList<>() ;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private ShineButton deleteLast;
private final static ArrayList<Integer> resourceIDs = new ArrayList<>();
Intent historiqueIntent;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView title = (TextView) findViewById(R.id.title_promo);
title.setTypeface(title.getTypeface(), Typeface.ITALIC);
deleteLast =(ShineButton)findViewById(R.id.deleteAll);
final MaterialSpinner spinner_search = (MaterialSpinner) findViewById(R.id.spinner);
// final Spinner spinner_search = (Spinner) findViewById(R.id.spinner);
ShineButton btn_search = (ShineButton) findViewById(R.id.searchView);
// spinner_search.setDropdownHeight(1000);
spinner_search.setDropdownMaxHeight(1000);
historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.Ville,android.R.layout.simple_spinner_dropdown_item);
// spinner_search.setAdapter(adapter);
VilleRemember vill = new VilleRemember(getBaseContext() , "" , 0 );
spinner_search.setSelectedIndex(vill.getindiceSelected());
spinner_search.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
VilleRemember vill = new VilleRemember(getBaseContext() , item,position );
vill.newSelectedVille(position,item);
}
});
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(historiqueIntent);}});
activity=this;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//rotateAnimation(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lanceScane(activity);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onResume()
{
// System.gc();
super.onResume();
}
//////////////////////////////////////
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page >= 4) { // In my case the number of pages are 5
// timer.cancel();
page = 0;
// viewPager.setCurrentItem(page--);
// Showing a toast for just testing purpose
/* Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show(); */
} else {
viewPager.setCurrentItem(page++);
}
}
});
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.accueil) {
// Handle the camera action
} else if (id == R.id.historique) {
Intent i = new Intent(this , Histourique.class);
startActivity(i);
} else if (id == R.id.prefere) {
Intent i = new Intent(this , Fav_class.class);
startActivity(i);
//overridePendingTransition(R.anim.slide_in_bottom,R.anim.slide_out_bottom);
} else if (id == R.id.parametre) {
Intent i = new Intent(this , Parametres.class);
startActivity(i);
} else if (id == R.id.propose_nous) {
startActivity(new Intent(MainActivity.this, About_us.class));
finish();
} else if (id == R.id.contactez_nous) {
Intent i = new Intent(this , contact_us.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void lanceScane(Activity activity)
{
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scanner");
integrator.setCameraId(0);
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
//historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//historiqueIntent.putExtra("serial",result.getContents());
//startActivity(historiqueIntent);
Intent i = new Intent(MainActivity.this,RechercheResult1.class);
i.putExtra("CodeBar",result.getContents());
Historique his = new Historique(this , result.getContents());
his.insert(result.getContents());
his.remplireDateCode();
startActivity(i);
Toast.makeText(this, "Done! " , Toast.LENGTH_SHORT).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onPause()
{
// System.gc();
super.onPause();
}
//------------------------------------------------------
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
page++;
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
page--;
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
// images dyal les produit proposses :
private void inflateThumbnails() {
System.out.println("==========>"+CodeBar.size());
TextView title = (TextView) findViewById(R.id.title_promo);
if(CodeBar.size() == 0)
{
title.setVisibility(View.INVISIBLE);
deleteLast.setVisibility(View.INVISIBLE);
}
else
{
title.setVisibility(View.VISIBLE);
deleteLast.setVisibility(View.VISIBLE);
}
thumbnailsContainer.removeAllViews();
for (int i = 0; i < CodeBar.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.cardview, null);
TextView price = (TextView) imageLayout.findViewById(R.id.prixprodtestcard);
TextView name = (TextView) imageLayout.findViewById(R.id.nomprodtestcard);
TextView namfou=(TextView) imageLayout.findViewById(R.id.qtestockcard);
TextView rating=(TextView)imageLayout.findViewById(R.id.rating);
ImageView imageProd = (ImageView) imageLayout.findViewById(R.id.imageprodcard);
FloatingActionButton btnlike = (FloatingActionButton) imageLayout.findViewById(R.id.likeButtoncard);
btnlike.setVisibility(View.INVISIBLE);
price.setText(prix.get(i));
name.setText(nomProd.get(i));
namfou.setText(nomFour.get(i));
rating.setText(ratings.get(i).toString());
imageProd.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow View pager to intercept touch events.
System.out.print("=============>ACTION_DOWN");
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
System.out.print("=============>ACTION_UP");
// Allow View pager to intercept touch events.
// v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle Listview touch events.
v.onTouchEvent(event);
return true;
}
});
Glide.with(this)
.load(new TagDatabase().URL_IMAGFOU+"fid="+id_Four.get(i)+"&&code="+CodeBar.get(i)+"&&etat= -99")
.diskCacheStrategy( DiskCacheStrategy.NONE )
.skipMemoryCache( true )
.placeholder(R.drawable.waitloat)
.thumbnail(0.1f)
.into(imageProd);
imageProd.setOnClickListener(onChagePageClickListener(i));
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),InformationsProduit.class);
intent.putExtra("nomProd", nomProd.get(i));
intent.putExtra("prix", prix.get(i));
intent.putExtra("nomFour",nomFour.get(i));
intent.putExtra("etatpromo", -99);//attttt
intent.putExtra("telFour",tel.get(i));
intent.putExtra("addrFour",adresse.get(i));
intent.putExtra("idFour",id_Four.get(i));
intent.putExtra("description",description.get(i));
intent.putExtra("codeBar",CodeBar.get(i));
startActivity(intent);
}
};
}
}

android-navigation drawer not open on activity change

it's weird , I spend last 5 hours on it , nothing worked. the problem is this ,When I go from activity a to activity b , and press back button and come back to activity a, the navigation drawer not open.
this is the code :
public abstract class DrawerActivity extends ActionBarActivity {
static LinearLayout fullLayout;
static FrameLayout actContent;
static DrawerLayout mDrawerLayout;
static ListView mDrawerList;
static ActionBarDrawerToggle mDrawerToggle;
static LinearLayout mDrawer;
List<HashMap<String, String>> mList;
SimpleAdapter mAdapter;
final private String COUNTRY = "country";
final private String FLAG = "flag";
final private String COUNT = "count";
#Override
public void setContentView(final int layoutResID) {
fullLayout= (LinearLayout) getLayoutInflater().inflate(R.layout.act_layout, null); // Your base layout here
actContent= (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true); // Setting the content of layout your provided to the act_content frame
super.setContentView(fullLayout);
makelist();
}
mTitle = (String) getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = (LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < mCountries.length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(COUNTRY, mCountries[i]);
hm.put(FLAG, Integer.toString(mFlags[i]));
mList.add(hm);
}
String[] from = { FLAG, COUNTRY };
int[] to = { R.id.flag, R.id.country };
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from,to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_navigation_drawer, R.string.drawer_open,R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedCountry();
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
Log.v("this","close");
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setAdapter(mAdapter);
}
public static boolean open() {
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
return true;
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
return true;
}
}
this is MainActivity class:
public class MainActivity extends DrawerActivity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//suppose this is the imageview on the actionbar
ImageView img=(ImageView)dialogg.findViewById(R.id.img);
dateup.img(new OnClickListener() {
#Override
public void onClick(View v) {
DrawerActivity.open();
}
});
}
one thing I want to notice , the mainActivity extends DrawerActivity class.
Could you help me to solve this ?
thanks you
This
trys to use the method open() from the Abstract class and you use "mDrawerLayout" and this must be null at this moment i think
public void onClick(View v) {
DrawerActivity.open();
}
maybe you use
public void onClick(View v) {
this.open();
}
Then you will use the open-Method of your current Activity
And you have to implement the onClickListener in the Activity
An error msg would be nice to get more information about the error

How can the back button in action bar act as the back button on device?

In Android if I start new Activity B from within activity A, Android will automatically save all the state of Activity A. So when I click back button on the device in Activity B, A will be restored to the state when I had started Activity B (for example: Spinners, ListView and Toggle Buttons all are in their previous positions).
BUT when I click the back button in action bar activity A starts fresh with no stored state.
Is there any way to make this back button similar to the device's back or I have to use SharedPreferences and store every thing myself?
(api 8 and above for my app)
In one of the fragments in my app I have a ListView which is one of the fragments that needs to be in the same state when coming back from the next page. I have added the code below.
If any other part is needed please tell me and I will add the code.
The main activity code:
private ProgressDialog progress;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(Farsi.Convert(getString(R.string.app_name_farsi)));
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab. We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter. Also specify this Activity object, which implements the TabListener interface, as the callback (listener) for when this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent=new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
EDIT:
All right. I changed my API level from 8 to 11 to.
Also I added getActionBar().setDisplayHomeAsUpEnabled(true); to onCreate() of activity.
And changes the onOptionsItemSelected as follows.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent=new Intent(PropertyDetailActivity.this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.up:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.homeAsUp:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
BUT none of the switch cases gets the chance to run when I click the back button in the action bar!

Categories

Resources