i'm trying to save object(saveMOvie) in onSaveinstanceState to restore it on screen rotated when debugging the code using tablet with main and detail fragments are next to each other the value of object (saveMOvie) is null but when using mobile phone with only one fragment on screen the value of object (saveMOvie) doesn't equal null could anyone tell me why ??
MainActivityFragment
public class MainActivityFragment extends Fragment {
Movie moviesStore[];
GridView gridView;
String[] moviesImages;
View rootView;
ImageAdapter imgadpt;
boolean flag;
OnNewsItemSelectedListener onis;
Movie saveMOvie = new Movie();
public interface OnNewsItemSelectedListener {
public void onMovieSelected(Movie movie);
}
public MainActivityFragment() {
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//3shan myy7slash duplicate
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
onis = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.open_settings_activity) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
//refresh used when there is no connection
} else if (id == R.id.Refresh_activity) {
onStart();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mode = prefs.getString(getString(R.string.key),
getString(R.string.default_value));
if (mode.equals("popular") || mode.equals("top_rated")) {
new FetchMovies().execute(mode);
} else {
if (flag) {
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
FavouriteActivityFragment fav = new FavouriteActivityFragment();
fragmentTransaction.replace(R.id.frag_main, fav);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Intent intent = new Intent(getActivity(), FavouriteActivity.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
transaction.commit();
flag = isTablet(getActivity());
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf == null && nf.isConnected() != true) {
Snackbar snackbar = Snackbar
.make(rootView, "Network Not Available", Snackbar.LENGTH_LONG)
.setAction("RECONNECT", new View.OnClickListener() {
#Override
public void onClick(View view) {
onStart();
}
});
snackbar.show();
}
updateMovies();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("movie",saveMOvie);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
onis.onMovieSelected(saveMOvie);
}
setHasOptionsMenu(true);
rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
return rootView;
}
public class FetchMovies extends AsyncTask<String, Void, Movie[]> {
private final String Log_Tag = FetchMovies.class.getSimpleName();
private Movie[] getMovieDataFromJson(String moviesJasonStr)
throws JSONException
{
final String lists = "results";
final String decription = "overview";
final String originalTitle = "original_title";
final String moviePoster = "poster_path";
final String userRating = "vote_average";
final String releaseDate = "release_date";
final String id = "id";
JSONObject moviesJason = new JSONObject(moviesJasonStr);
JSONArray moviesArray = moviesJason.getJSONArray(lists);
// String[] resultStrs = new String[moviesArray.length()];
moviesStore = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject oneMovieInfo = moviesArray.getJSONObject(i);
moviesStore[i] = new Movie();
moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview"));
moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average"));
moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date"));
moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title"));
moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path"));
moviesStore[i].setId(oneMovieInfo.getString("id"));
}
return moviesStore;
}
#Override
protected Movie[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJasonStr = null;
StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/");
baseUrl.append(params[0]);
baseUrl.append("?api_key=");
baseUrl.append(BuildConfig.MOVIE_DP_API_KEY);
try {
// URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6");
URL url = new URL(baseUrl.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
moviesJasonStr = buffer.toString();
Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr);
} catch (IOException e) {
Log.e(Log_Tag, "Error ", e);
// Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(Log_Tag, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(moviesJasonStr);
} catch (JSONException e) {
Log.e(Log_Tag, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Movie[] result) {
if (result != null) {
moviesImages = new String[result.length];
for (int i = 0; i < result.length; i++) {
StringBuilder baseUrl = new StringBuilder();
baseUrl.append("http://image.tmdb.org/t/p/w185/");
baseUrl.append(result[i].getMoviePoster());
moviesImages[i] = baseUrl.toString();
}
imgadpt = new ImageAdapter(getActivity(), moviesImages);
gridView.setAdapter(imgadpt);
// if(flag){
// onis.onMovieSelected(moviesStore[0]);}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String posterUrl = (String) imgadpt.getItem(position);
saveMOvie = moviesStore[position];
if (flag) {
onis.onMovieSelected(moviesStore[position]);
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie", moviesStore[position]);
startActivity(intent);
}
}
});
} else {
Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show();
}
}
}
}
When onCreate(savedInstanceState) is called, check whether savedInstanceState is null, and if not, then getExtras from it (as it's a Bundle).
if (savedInstanceState != null)
savedInstanceState.getParcelable(key)
Then do whatever you'd like with the object.
Related
I created app that takes JSON with AsyncTask from server. When User click a button app starts new Activity and download data from server and show it as a items in ListView. The Problem is when I open new Activity it takes too long to load. When button is pressed app freeze on about one or two seconds and then show black screen for another 2/3 seconds. After that activity is displayed but it is very slow. It freeze every time user is scrolling or pressing button to display more options of custom adapter. Is there any way to make app more smooth? Json data that is downloaded is just simple JSONArray with JSONObjects that has 2 string values and one HTML format. This 3 values is display to user.
Part of Custom Adapter class
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
SuggestionList suggestionList = getItem(position);
int actualPosition = 0;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sugestion_list, parent, false);
}
final Button suggestionsButton = (Button) convertView.findViewById(R.id.suggestionsMore);
final TextView suggestionNumber = (TextView) convertView.findViewById(R.id.sugestionNumber);
final TextView suggestionDescription = (TextView) convertView.findViewById(R.id.suggestionDescription);
final ImageView bio = convertView.findViewById(R.id.sugestionBio);
final ImageView block = convertView.findViewById(R.id.sugestionBlock);
final ImageView call = convertView.findViewById(R.id.sugestionCall);
...
final Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slideup);
final Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slidedown);
final Handler handler = new Handler();
suggestionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (bioSuggestions.getVisibility() == View.GONE) {
bio.setVisibility(View.VISIBLE);
block.setVisibility(View.VISIBLE);
call.setVisibility(View.VISIBLE);
bioSuggestions.startAnimation(slideUp);
blockSuggestions.startAnimation(slideUp);
callSuggestions.startAnimation(slideUp);
} else if (bioSuggestions.getVisibility() == View.VISIBLE) {
bioSuggestions.startAnimation(slideDown);
blockSuggestions.startAnimation(slideDown);
callSuggestions.startAnimation(slideDown);
handler.postDelayed(new Runnable() {
#Override
public void run() {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
}, 300);
}
}
});
if (actualPosition != position) {
if (bio.getVisibility() == View.VISIBLE) {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
actualPosition = position;
}
JSONObject jsonValSuggestions = new getSugestions().sugestionsDetails(position, "suggestions");
try {
final String name = jsonValSuggestions.getString("client_name");
final String num = jsonValSuggestions.getString("client_number");
final String description = jsonValSuggestions.getString("client_description");
bio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionsDetails = new Intent(view.getContext(), SuggestionsDetails.class);
suggestionsDetails.putExtra("client_number", num);
suggestionsDetails.putExtra("client_name", name);
suggestionsDetails.putExtra("client_description", description);
activity.startActivityForResult(suggestionsDetails, position);
}
});
block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionBlock = new Intent(view.getContext(), BlockSuggestionsActivity.class);
activity.startActivity(suggestionBlock);
}
});
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionCall = new Intent(view.getContext(), CallSuggestionActivity.class);
suggestionCall.putExtra("client_number", num);
suggestionCall.putExtra("client_name", name);
activity.startActivity(suggestionCall);
}
});
} catch (Exception e) {
e.printStackTrace();
}
try {
if (suggestionList.suggestionName.equals("null") || suggestionList.suggestionName.equals("")) {
suggestionNumber.setText(suggestionList.suggestionNumber);
} else {
suggestionNumber.setText(suggestionList.suggestionName);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription, Html.FROM_HTML_MODE_LEGACY));
} else {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription));
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
}
return convertView;
}
Part of AsyncTask class
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String clientUrl = params[0];
String result;
String inputLine;
JSONObject obj;
String data;
String message;
try {
URL myUrl = new URL(clientUrl);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
public String[] getSuggestionsList() {
String[] suggestionList = new String[5];
String result;
String status;
JSONObject listObj;
String suggestionsData;
JSONObject suggestionsDataObj;
JSONArray suggestionsDataArr;
String ClientsSugestionsUrl = "https://example.com/token=" + authToken;
getApiClientSugestions getSugestionsFromApi = new getApiClientSugestions();
try {
result = getSugestionsFromApi.execute(ClientsSugestionsUrl).get();
try {
listObj = new JSONObject(result);
status = listObj.getString("result");
suggestionsData = listObj.getString("suggestions");
suggestionsDataArr = new JSONArray(suggestionsData);
} catch (Exception e) {
e.printStackTrace();
suggestionsDataArr = null;
status = null;
}
suggestionList[3] = status;
suggestionList[4] = suggestionsDataArr.toString();
} catch (Exception e) {
e.printStackTrace();
}
return suggestionList;
}
Activity
public class CallsSuggestionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calls_suggestions);
Slidr.attach(this);
getSupportActionBar().setTitle("Skontaktuj siÄ™");
}
#Override
protected void onResume() {
super.onResume();
CallsSuggestionList();
}
public void CallsSuggestionList() {
final ListView suggestionList = findViewById(R.id.sugestionList);
final ArrayList<SuggestionList> suggestionArray = new ArrayList<SuggestionList>();
SuggestionListAdapter suggestionListAdapter = new SuggestionListAdapter(getContext(), suggestionArray, this);
String[] suggestionListArray = new getSugestions().getSuggestionsList();
String suggStat = suggestionListArray[3];
String arrayList = suggestionListArray[4];
String clientName;
String clientNumber;
String clientDescription;
try {
JSONArray jsonArray = new JSONArray(arrayList);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
clientName = explrObject.getString("client_name");
clientNumber = explrObject.getString("client_number");
clientDescription = explrObject.getString("client_description");
if (suggStat.equals("true")) {
SuggestionList suggestionList1 = new SuggestionList(clientName, clientDescription, clientNumber);
suggestionListAdapter.addAll(suggestionList1);
suggestionListAdapter.notifyDataSetChanged();
suggestionList.setAdapter(suggestionListAdapter);
}
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
e.printStackTrace();
clientName = null;
clientDescription = null;
clientNumber = null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SuggestionList
public class SuggestionList {
public String suggestionNumber;
public String suggestionDescription;
public String suggestionCallType;
public String suggestionName;
public SuggestionList(
// String suggestionCallType,
String suggestionName, String suggestionDescription, String suggestionNumber) {
this.suggestionNumber = suggestionNumber;
// this.suggestionCallType = suggestionCallType;
this.suggestionName = suggestionName;
this.suggestionDescription = suggestionDescription;
}
}
Adapter are custom with custom view displayed to user. I use similar custom adapter to show content from sqlite that is on phone and there app isn't so slow. But when I open this activity it slow down dramatically. Also I noticed when I press back button it take very long to back to previous screen.
The problem is in the getSuggestionsList function. in this function, you are calling getSugestionsFromApi.execute(ClientsSugestionsUrl).get(); which make your code sync again. I mean your code is waiting this code to be executed.
One way (not right way, but easy way): you can call new getSugestions().getSuggestionsList(); in a new thread.
Second way, call getSugestionsFromApi.execute(ClientsSugestionsUrl) without get() function. But to get result of the code, you need to give an interface.
To get right usage: https://xelsoft.wordpress.com/2014/11/28/asynctask-implementation-using-callback-interface/
can any one suggest me how to get all network connected to my wifi . i want to identify specific network among them and then that all specific network should display in listview.
Here is sample how to get wifi connected devices ip
https://github.com/SupunArunoda/ChatWithoutInternet
private WifiApiManager wifiApManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_sharing);
wifiApManager = new WifiApiManager(this);
listView = (ListView) findViewById(R.id.listView2);
username = (String) getIntent().getExtras().get("name");
SelectClient sendImage = new SelectClient();
sendImage.execute((Void) null);
}
//Asynchronous class to select Client
private class SelectClient extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
final ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false);
runOnUiThread(new Runnable() {
#Override
public void run() {
ClientScanResult clientScanResult;
values = new String[clients.size()];
for (int i = 0; i < clients.size(); i++) {
clientScanResult = clients.get(i);
values[i] = "IpAddress: " + clientScanResult.getIpAddress();//store client's ip addresses in values array
}
adapter = new ArrayAdapter<>(ClientSelectActivity.this, R.layout.list_white_text, R.id.list_content, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
i = new Intent(ClientSelectActivity.this, PrivateChatActivity.class);
i.putExtra("ipAddress",clients.get(position).getIpAddress());
i.putExtra("name", username);
startActivity(i);//start activity from this activity to PrivateChatActivity
}
});
}
});
return true;
}
}
//class to manage WiFi technology
public class WifiApiManager {
private final WifiManager mWifiManager;
public WifiApiManager(Context context) {
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
return getClientList(onlyReachables, 300);
}
//function to return available clients
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
BufferedReader br = null;
ArrayList<ClientScanResult> result = null;
try {
result = new ArrayList<>();
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if ((splitted != null) && (splitted.length >= 4)) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachables || isReachable) {
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
}
}
}
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage());
} finally {
try {
br.close();
} catch (IOException e) {
Log.e(this.getClass().toString(), e.getMessage());
}
}
return result;
}
}
I am trying to access a file twice in my program.
First I am reading from the file, which runs fine.
The second time, I am trying to delete the same file from which I read.
Strangely the second time no records are present in the file. In fact when I try to run the command file.exists it returns false. Why is this happening?
Following is my code:
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List<ROOM> mRoomList;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup,menu);
}
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
File filemain = new File("roomdata.txt");
try {
File temp = File.createTempFile("file",".txt",filemain.getParentFile());
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(temp), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
int p=0;
for(String line; (line=reader.readLine())!=null;) {
if(p == pos) {
line = line.replace(line,"");
writer.println(line);
}
writer.println(line);
}
reader.close();
writer.close();
filemain.delete();
temp.renameTo(filemain);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.Edit:
return true;
case R.id.Delete:
filedel(info.position);
mRoomList.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = (new File("roomdata.txt").exists());
Toast.makeText(getApplicationContext(), String.valueOf(exists), Toast.LENGTH_LONG).show();
FileInputStream fis = openFileInput("roomdata.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] data = new char[block];
String roomdata = "";
int size;
try {
while ((size = isr.read(data)) > 0) {
String read_data = String.copyValueOf(data, 0, size);
roomdata += read_data;
data = new char[block];
}
} catch (IOException e) {
e.printStackTrace();
}
String[] room_display = roomdata.split("\n");
String[] tempstring;
ListView lsv = (ListView) findViewById(R.id.Room_list);
mRoomList = new ArrayList<>();
for (int b = 0; b < room_display.length; b++) {
tempstring = room_display[b].split(":");
mRoomList.add(new ROOM(tempstring[0], tempstring[1], tempstring[2], tempstring[3], tempstring[4], tempstring[5], tempstring[6], tempstring[7], tempstring[8], tempstring[9]));
}
adapter = new RoomListAdapter(getApplicationContext(), mRoomList);
lsv.setAdapter(adapter);
registerForContextMenu(lsv);
int count = mRoomList.size();
final ArrayList<Integer> disabledpos = new ArrayList<Integer>();
for (int q = 0; q < count; q++) {
ROOM temp_room1 = mRoomList.get(q);
String IP = temp_room1.getRoom_IP_Address();
String online = null;
ConnectionTest CT = new ConnectionTest();
try {
online = CT.execute(IP, "a", "b").get();
Boolean b1 = Boolean.valueOf(online);
if (!b1) {
disabledpos.add(q);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
try {
isr.reset();
isr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (new File("roomdata.txt").delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
lsv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int temp_position = position;
Intent p = new Intent(ControlLights.this, Electrical_equipment_list.class);
if (!(disabledpos.contains(position))) {
ROOM temp_room = mRoomList.get(temp_position);
p.putExtra("EE1", temp_room.getEE1());
p.putExtra("EE2", temp_room.getEE2());
p.putExtra("EE3", temp_room.getEE3());
p.putExtra("EE4", temp_room.getEE4());
p.putExtra("EE5", temp_room.getEE5());
p.putExtra("EE6", temp_room.getEE6());
p.putExtra("EE7", temp_room.getEE7());
p.putExtra("EE8", temp_room.getEE8());
p.putExtra("IPaddress", temp_room.getRoom_IP_Address());
startActivity(p);
}
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
loadrooms();
}
public class ConnectionTest extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
Boolean online;
String tempstring = null;
try {
InetAddress roomaddress = InetAddress.getByName(params[0]);
online = roomaddress.isReachable(100);
tempstring = String.valueOf(online);
} catch (IOException e) {
e.printStackTrace();
}
return tempstring;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
Keep your File as a class' member, since it is an essential component of what the class does
Move your inner logic and file reference initialization to onStart()
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List mRoomList;
private File filemain;
...
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
try {
File temp = File.createTempFile("file",".txt", filemain.getParentFile());
...
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = filemain.exists();
...
if (filemain.delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
} ...
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
}
#Override
protected void onStart() {
super.onStart();
filemain = new File("roomdata.txt");
loadrooms();
}
}
Foot note
I apologize for the horrible code format, but apparently they changed the parsing algorithm to a point where you have to manually type all the code again here instead of just being able to copy-paste it. Anyone being to edit it accordingly is welcome.
When i start up the app it loads all the movie posters correctly. When i click on a poster it should start DetailActivity and display the poster i selected. However every poster i click all displays the same one.
MainActivityFragment
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final int MOVIE_LOADER = 0;
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
private static final String[] MOVIE_COLUMNS = {
MovieContract.MovieEntry.TABLE_NAME + "." + MovieContract.MovieEntry._ID,
MovieContract.MovieEntry.COLUMN_MOVIE_POSTER
};
static final int COL_MOVIE_ID = 0;
static final int COL_MOVIE_URL = 1;
private MovieAdapter mMovieAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMovieAdapter = new MovieAdapter(getActivity(),null,0);
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.movieposter_image_gridview);
gridView.setAdapter(mMovieAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
Cursor cursor = (Cursor)adapterView.getItemAtPosition(position);
if(cursor != null){
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(MovieContract.MovieEntry.CONTENT_URI);
startActivity(intent);
Log.d("DEBUG", "Selected item position " + position + ", with id: " + l);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
getLoaderManager().initLoader(MOVIE_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateApplication() {
FetchMovieTask movieTask = new FetchMovieTask(getActivity());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = prefs.getString(getString(R.string.pref_sort_by_key),
getString(R.string.pref_popular_default));
movieTask.execute(sortBy);
}
#Override
public void onStart() {
super.onStart();
updateApplication();
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle){
Uri movieUri = MovieContract.MovieEntry.CONTENT_URI;
return new CursorLoader(getActivity(),
movieUri,
MOVIE_COLUMNS,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor){
mMovieAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader){
mMovieAdapter.swapCursor(null);
}
}
DetailActivity
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DetailFragment extends Fragment implements LoaderCallbacks<Cursor> {
private final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String Movie_SHARE_HASHTAG = " #MovieApp";
private ShareActionProvider mShareActionProvider;
private String mMovie;
ImageView poster;
private static final int DETAIL_LOADER = 0;
private final String[] DETAIL_COLUMNS = {
MovieContract.MovieEntry.TABLE_NAME + "." + MovieContract.MovieEntry._ID,
MovieContract.MovieEntry.COLUMN_MOVIE_POSTER
};
private static final int COL_MOVIE_ID = 0;
private static final int COL_MOVIE_POSTER = 1;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "In onCreateLoader");
Intent intent = getActivity().getIntent();
if (intent == null) {
return null;
}
return new CursorLoader(
getActivity(),
intent.getData(),
DETAIL_COLUMNS,
null,
null,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG, "In onLoadFinished");
if (!data.moveToFirst()) {
return;
}
String posterURL = data.getString(COL_MOVIE_POSTER);
final String POSTERIMAGE_BASE_URL = "http://image.tmdb.org/t/p/";
final String POSTERIMAGE_SIZE = "w500";
poster = (ImageView) getView().findViewById(R.id.detailActivity_image_view);
final String POSTERIMAGE_URL = POSTERIMAGE_BASE_URL + POSTERIMAGE_SIZE + posterURL;
Picasso.with(this.getActivity()).load(POSTERIMAGE_URL).into(poster);
Log.v(LOG_TAG, "Poster Urls: " + POSTERIMAGE_URL);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
MovieAdapter
public class MovieAdapter extends CursorAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
public MovieAdapter(Context context, Cursor c, int flags){
super(context,c,flags);
}
private String convertCursorRowToUXFormat(Cursor cursor){
String poster = cursor.getString(MainActivityFragment.COL_MOVIE_URL);
return poster;
}
#Override
public View newView(Context context,Cursor cursor,ViewGroup parent){
View view = LayoutInflater.from(context).inflate(R.layout.poster_image, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final String POSTERIMAGE_BASE_URL = "http://image.tmdb.org/t/p/";
final String POSTERIMAGE_SIZE = "w500";
ImageView posterImage = (ImageView)view;
final String POSTERIMAGE_URL = POSTERIMAGE_BASE_URL + POSTERIMAGE_SIZE + convertCursorRowToUXFormat(cursor);
Picasso.with(context).load(POSTERIMAGE_URL).into(posterImage);
Log.v(LOG_TAG, "Poster Urls: " + POSTERIMAGE_URL);
}
}
FetchMovieTask
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
private final Context mContext;
public FetchMovieTask(Context context) {
mContext = context;
}
private boolean DEBUG = true;
private void getMovieDataJSON(String movieJSONStr)
throws JSONException {
final String MDB_RESULT = "results";
final String MDB_POSTER = "poster_path";
final String MDB_MOVIE_TITLE = "original_title";
final String MDB_MOVIE_PLOT = "overview";
final String MDB_MOVIE_RATING = "popularity";
final String MDB_RELEASE_DATE = "release_date";
try {
JSONObject movieJSON = new JSONObject(movieJSONStr);
JSONArray movieArray = movieJSON.getJSONArray(MDB_RESULT);
Vector<ContentValues> cVVector = new Vector<>(movieArray.length());
for (int i = 0; i < movieArray.length(); i++) {
String poster;
String title;
String plot;
String rating;
String releaseDate;
//Get theJSON object representing the movie
JSONObject movieDetail = movieArray.getJSONObject(i);
poster = movieDetail.getString(MDB_POSTER);
title = movieDetail.getString(MDB_MOVIE_TITLE);
plot = movieDetail.getString(MDB_MOVIE_PLOT);
rating = movieDetail.getString(MDB_MOVIE_RATING);
releaseDate = movieDetail.getString(MDB_RELEASE_DATE);
ContentValues movieDetailValues = new ContentValues();
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_NAME, title);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_POSTER, poster);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_PLOT, plot);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_RATING, rating);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_REDATE, releaseDate);
cVVector.add(movieDetailValues);
}
int inserted = 0;
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchMovieTask Complete. " + inserted + " Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
#Override
protected Void doInBackground (String...params){
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJSONStr = null;
try {
final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie";
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter("api_key", BuildConfig.MOVIE_API_KEY)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
movieJSONStr = buffer.toString();
getMovieDataJSON(movieJSONStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
}
catch(JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
}
You need to update variable COL_MOVIE_POSTER in DetailActivity according to item clicked in gridview of MainActivityFragment.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}