I have a main activity extending ActionBarActivity. In my activity i create a fragment which isn't showing up. I modified the main activity to extend FragmentActivity and in this case the fragment is showing up. Why isn't the fragment showing up when my activity extends ActionBarActivity? I know that ActionBarActivity extends FragmentActivity so in theory ActionBarActivity should support fragments.
Edit: I resolved it. I wouldn't set any content view on my activity. Now that i set it it works when i extend ActionBarActivity. Still is weird that even if i don't set it, when i extend FragmentActivity it works.
This is my main activity code:
package com.example.yamba;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class StatusActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
{
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.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.status, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my fragment code:
package com.example.yamba;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.AsyncTask;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.marakana.android.yamba.clientlib.YambaClient;
import com.marakana.android.yamba.clientlib.YambaClientException;
public class StatusFragment extends Fragment implements OnClickListener
{
private static final String TAG = "StatusFragment";
private EditText editStatus;
private Button buttonTweet;
private TextView textCount;
private int defaultColor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_fragment, container, false);
editStatus = (EditText) view.findViewById (R.id.editStatus);
buttonTweet = (Button) view.findViewById (R.id.buttonTweet);
textCount = (TextView) view.findViewById (R.id.textCount);
buttonTweet.setOnClickListener(this);
defaultColor = textCount.getTextColors().getDefaultColor();
editStatus.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged (Editable s)
{
int count = 140 - editStatus.length();
textCount.setText(Integer.toString(count));
textCount.setTextColor(Color.GREEN);
if(count<20 && count >= 10)
textCount.setTextColor(Color.YELLOW);
else if (count<10)
textCount.setTextColor(Color.RED);
else
textCount.setTextColor(defaultColor);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged (CharSequence s, int start, int b, int c){}
});
return view;
}
public void onClick(View view)
{
String status = editStatus.getText().toString();
Log.d(TAG, "onClicked with status: " + status);
new PostTask().execute(status);
editStatus.getText().clear();
}
private final class PostTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
YambaClient yambaCloud = new YambaClient("student", "password");
try
{
yambaCloud.postStatus(params[0]);
return "Succesfuly posted!";
}
catch (YambaClientException e)
{
e.printStackTrace();
return "Failed to post to yamba sevice!";
}
}
#Override
protected void onPostExecute (String result)
{
super.onPostExecute(result);
Toast.makeText(StatusFragment.this.getActivity(), result, Toast.LENGTH_LONG).show();
}
}
}
You are calling the FragmentManager method add into the wrong container. The id you provide must reference to a View (usually a layout) that is part of your activity's layout. So android.R.id.content is surely wrong, look into your activity xml layout and find the correct id (maybe is R.id.content (without android) ? )
It appears to be a bug. As a workaround you could try to add fragment inside a post command. It did the trick for me.
new Handler().post(new Runnable() {
#Override
public void run() {
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
});
Related
I have a custom viewPagerAdapter in this activity, when the first launch of the activity (When the main activity starts it with the intent) the pager displays the fragments correctly, but when I rotate the device, the recipe is got from the savedInstantState, and the adapter is started, but the fragments are not displayed and the getItem method doesn't get callled!
Here's the code for the Activity:
package com.ameer.bake.activities;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.ameer.bake.Constants;
import com.ameer.bake.fragments.IngredientsFragment;
import com.ameer.bake.fragments.StepDetailsFragment;
import com.ameer.bake.fragments.StepsFragment;
import com.ameer.bake.R;
import com.ameer.bake.models.Recipe;
import com.ameer.bake.models.Step;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class DetailsActivity extends AppCompatActivity implements StepsFragment.StepCallback{
private Recipe recipe;
private IngredientsFragment ingredientsFragment;
private StepsFragment stepsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState != null){
recipe = new Gson().fromJson(savedInstanceState.getString(Constants.RECIPE), Recipe.class);
setupViewPager();
} else if (getIntent().hasExtra(Constants.CURRENT_RECIPE_KEY) ) {
Gson gson = new Gson();
recipe = gson.fromJson(getIntent().getStringExtra(Constants.CURRENT_RECIPE_KEY), Recipe.class);
setTitle(recipe.getName());
setupViewPager();
}
}
#Override
public void onStepClicked(Step step) {
Intent intent = new Intent(DetailsActivity.this, StepActivity.class);
intent.putExtra(Constants.STEP_KEY, new Gson().toJson(step));
startActivity(intent);
}
private class RecipePagerAdapter extends FragmentPagerAdapter {
private static final int NUM_ITEMS = 2;
private final String[] titles = new String[]{
getString(R.string.ingredients), getString(R.string.steps)};
private RecipePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
if (ingredientsFragment == null && stepsFragment == null) {
ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setIngredients(recipe.getIngredients());
stepsFragment = new StepsFragment();
stepsFragment.setSteps(recipe.getSteps());
stepsFragment.setCallback(DetailsActivity.this);
}
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ingredientsFragment;
case 1:
return stepsFragment;
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(Constants.RECIPE, new Gson().toJson(recipe));
super.onSaveInstanceState(savedInstanceState);
}
private void setupViewPager(){
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
FragmentPagerAdapter pagerAdapter = new RecipePagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(pagerAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpager_tab);
viewPagerTab.setViewPager(vpPager);
}
}
Switch to a FragmentStatePagerAdapter rather than using FragmentPagerAdapter. Also use getChildFragmentManager() instead of getSupportFragmentManager()
The solution was as Pedro Varela mentioned in the comments:
"Hope this works. Add setRetainInstance(true); in onCreate of your internal fragments of the view pager "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated""
Thanks
package com.example.android.sunshine;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
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 void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
MenuItem menuItem=menu.findItem(R.id.action_share);
ShareActionProvider mShareActionProvider= (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
if(mShareActionProvider!=null)
{
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
else
{
Log.d(LOG_TAG,"Amen");
}
//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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecastStr;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text)).setText(mForecastStr);
}
return rootView;
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
}
}
In the code above when the line in the onCreateOptionsMenu where I use LOG_TAG and where I use createShareForecastIntent says cannot resolve symbol and method. I tried googling it but couldn't find anything. I am new to android and java both.
You need to define LOG_TAG in your DetailActivity first as such:
private static final String LOG_TAG = "Some tag string";
Declare createShareForecastIntent as static since FORECAST_SHARE_HASHTAG is static. if you want to use them inside a non-static class method, you can either declare it public and call it like this: DetailFragment.FORECAST_SHARE_HASHTAG, or simply declare the method that's using it without class reference as static.
i.e.:
public static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
// call it like this, referencing the class name
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + DetailFragment.FORECAST_SHARE_HASHTAG);
I'd like to pass back user typed string in the dialog fragment: "AddFriendDialogFragment.java" back to the activity that had called it: "HomeActivity.java". I'm doing this thru an interface declared inside "AddFriendDialogFragment.java": "EditNameDialogListener". However for some reason, HomeActivity is not seeing this interface, so I'm getting a "Cannot resolve symbol: "EditNameDialogListener" error.
"HomeActivity.java":
package tutorial.com.example.jerryhou.dialogactionbartutorial;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class HomeActivity extends Activity implements EditNameDialogListener
{
#Override
public void onFinishEditDialog(String inputText)
{
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
public void showUsernameSearchDialog(View v)
{
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new AddFriendDialogFragment();
newFragment.show(fragmentManager, "AddFriendDialog");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#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_home, 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;
}
return super.onOptionsItemSelected(item);
}
}
"AddFriendDialogFragment.java":
package tutorial.com.example.jerryhou.dialogactionbartutorial;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
public class AddFriendDialogFragment extends DialogFragment
{
private static final String TAG = "AddFriendDialogFragment";
public interface EditNameDialogListener
{
void onFinishEditDialog(String inputText);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View addFriendDialogView = inflater.inflate(R.layout.fragment_add_friend_dialog, null);
// Set an EditText view to get user input
final EditText usernameEditText = (EditText) addFriendDialogView.findViewById(R.id.username);
builder.setView(addFriendDialogView)
// Add action buttons
.setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
{
//Retrieve Username typed in
String username_querystr = usernameEditText.getText().toString();
//Correctly retrieving query str
Log.v(TAG, "Going to search " + username_querystr);
//Pass back query str to search in HomeActivity
EditNameDialogListener activity = (EditNameDialogListener) getActivity();
activity.onFinishEditDialog(usernameEditText.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AddFriendDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
Even if they are in the same package, you can't use EditNameDialogListener directly as it's an inner interface.
You have 2 choices here :
-> Use EditNameDialogListener fully qualified name, i.e AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
-> Import explicitly EditNameDialogListener
import tutorial.com.example.jerryhou.dialogactionbartutorial.AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements EditNameDialogListener
The name of the implemented interface should be AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
You could either copy the interface into a separate compilation unit / file
OR
probably using the static scope identifier in front your interface
public static interface EditNameDialogListener
{...}
and something like #Hacketo mentioned will help:
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
How to create a task with OnClickListener???
I Tryed with two methods (AsyncTask & Runnable/Thread):
I have test the AsyncTask Method:
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask(getActivity()).execute("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
}
});
return rootView;
}
}
}
class LoginTask extends AsyncTask<String, Integer, Long> {
private FragmentActivity activity;
public LoginTask(FragmentActivity activity) {
this.activity = activity;
}
protected Long doInBackground(String... urls) {
try{
URL oracle = new URL(urls[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(activity, "Failed", Toast.LENGTH_LONG).show();
}
return (long) 0;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
and i have tested a Runnable Method
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Runnable run = new Runnable() {
#Override
public void run() {
try{
URL oracle = new URL("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(getActivity(), "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
};
Thread t = new Thread(run);
t.start();
}
});
return rootView;
}
}
}
but this two Methods dosent works.
I noticed, that you called Toast.makeText(...).show() from doInBackground(). It will not work. I wish I could write this as a comment, but I don't have enough reputation...
Also, URLEncoder.encode() is deprecated. Try encode with encoding as the second argument.
And in the end, usually, network operations are implemented using HttpUrlConnection or DefaultHttpClient (the first is preferable). Here you can find a code snippet.
I have a listview that uses a custom arrayadapter that loads a layout with text + a radiobutton. The user should only be able to select a single item in the list at a time - so basically only one radio button should be 'checked' at any time. This works perfectly except when the activity is recreated, like when the screen is rotated. I can't figure out why it's doing this, so maybe you all can think of something?
Here's the code for the activity that has the listview:
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.widget.AdapterView;
public class TimeForm extends Activity implements AdapterView.OnItemClickListener {
private MyArrayAdapter maa;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_form);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(false);
String listitems[] = new String[16];
listitems[0] = "Other";
for(int i = 1; i < 16; i++)
{
listitems[i] = "Job " + i;
}
maa = new MyArrayAdapter(this, R.layout.layout_list, listitems);
if(savedInstanceState != null)
maa.selIndex = savedInstanceState.getInt("selIndex");
lv.setAdapter(maa);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
EditText et = (EditText) this.findViewById(R.id.editText1);
if(position == 0)
{
et.setVisibility(View.VISIBLE);
} else {
et.setVisibility(View.GONE);
}
if(maa.selItem != null)
{
RadioButton rOld = (RadioButton) maa.selItem.findViewById(R.id.radioButton1);
rOld.setChecked(false);
}
RadioButton r = (RadioButton) view.findViewById(R.id.radioButton1);
r.setChecked(true);
maa.selIndex = position;
maa.selItem = view;
}
public void onSaveInstanceState(Bundle b)
{
b.putInt("selIndex", maa.selIndex);
super.onSaveInstanceState(b);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_time_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Code for MyArrayAdapter class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private Context context;
private String[] strings;
private int layoutID;
public int selIndex;
public View selItem;
public MyArrayAdapter(Context c, int id, String[] values)
{
super(c, id, values);
selIndex = -1;
selItem = null;
this.strings = values;
this.context = c;
layoutID = id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rView = inflater.inflate(layoutID, parent, false);
TextView tv = (TextView) rView.findViewById(R.id.textView1);
tv.setText(strings[position]);
if(position == selIndex)
{
RadioButton r = (RadioButton) rView.findViewById(R.id.radioButton1);
r.setChecked(true);
selItem = rView;
}
return rView;
}
}
Well, first thing's first, with regards to 're-creating' the view.. check out http://developer.android.com/guide/topics/resources/runtime-changes.html.
You can define public void onConfigurationChanged(Configuration newConfig) to ensure that your activity isn't recreated on rotation, for example.
That said, if you want to persist the values, you'll have to actually do that, and then apply any selections to your collection passed into your ArrayAdapter.
I figured it out. I'm not sure it's the best possible solution, but it works and doesn't cause any noticeable performance loss. ^_^
In the TimeForm activity's onItemClick() method, i added this at the bottom:
ListView lv = (ListView) findViewById(R.id.listView1);
lv.invalidateViews();
This forces the listview to redraw all the child views. Thanks to everyone who took the time to help me figure this out.