Not able to resolve identify member class attribute in android studio - java

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);

Related

Why was there a run error with some functions?

MainActivity mActivity = new MainActivity();
mActivity.countRecords();
The Way I Used to call function countRecords() Which it was inside OnClickListenerCreateStudent class But I found the message when the button is pressed but with this a way no problems
((MainActivity)context).countRecords(); What is the difference between them now ?
package com.example.train1;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonCreateLocation = (Button) findViewById(R.id.buttonCreateStudent);
buttonCreateLocation.setOnClickListener(new OnClickListenerCreateStudent());
countRecords();
}
public void countRecords() {
int recordCount = new TableControllerStudent(this).count();
TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package com.example.train1;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
public class OnClickListenerCreateStudent implements View.OnClickListener {
//MainActivity M_activity;
//MainActivity mActivity// = new MainActivity();
#Override
public void onClick(View view) {
//M_activity = new MainActivity();
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);
final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);
new AlertDialog.Builder(context).setView(formElementsView).setTitle("Create Student")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
// countRecords();
public void onClick(DialogInterface dialog, int id) {
String studentFirstname = editTextStudentFirstname.getText().toString();
String studentEmail = editTextStudentEmail.getText().toString();
ObjectStudent objectStudent = new ObjectStudent();
objectStudent.firstname= studentFirstname;
objectStudent.email= studentEmail;
// call to table controller stud and put objectData
boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);
if(createSuccessful){
Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
}
((MainActivity)context).countRecords();
MainActivity mActivity = new MainActivity();
mActivity.countRecords();
//((MainActivity)).
dialog.cancel();
}
}).show();
// Toast.makeText(context," "+context , Toast.LENGTH_LONG).show();
}
public class ObjectStudent {
int id;
String firstname;
String email;
public ObjectStudent(){
}
}
// class End
}
Never create your activities with the constructor, they're bound to not be initialized correctly sooner or later.
Create the Activity via the Intent, as in the docs:
Intent intent = new Intent(this, DisplayMessageActivity.class);

Can't get To Do Activity to work in a fragment

sorry I'm fairly new to android so I seem to keep getting stuck on the simplest things.
I had two projects I had completed for a class. One was a simple To Do List and another that allowed different fragments to be used depending on whether you are in portrait or landscape mode. both worked but when trying to combine the two I get an error when put my To Do activity in the fragment if I extend Fragment (findByViews and setContentView dont work.
I can replace Fragment with FragmentActivity which fixes this but then my MainActivity.java's fragmentTransaction.replace(android.R.id.content, pm_fragment); gets an error saying:
"replace (int, android.app.Fragment) in FragmentTransaction cannot be applied to (int, com.android.MyFragmentsTodo.PM_Fragment)"
Can anyone tell me what I can do to make this work? I have a test tomorrow and I'm worried the lecturer might want us to mix an activity with fragments.
Any help would be greatly appreciated.
MainActivity.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//check device orientation and act upon it
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
// If orientation is landscape then
LM_Fragment ls_fragment = new LM_Fragment();
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
// If orientation is portrait then
PM_Fragment pm_fragment = new PM_Fragment();
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
//apply (commit) the changes
fragmentTransaction.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.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;
}
return super.onOptionsItemSelected(item);
}
}
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends android.support.v4.app.Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return inflater.inflate(R.layout.lm_fragment, container, false);
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
return true;
}
});
}
#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;
}
return super.onOptionsItemSelected(item);
}
public void AddItem(View view) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}
OK i have figured out how to fix the issue. One must keep extending Fragment but when doing using findViewById one must use:
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
and then precede all findViewById's with rootView like this:
listView = (ListView) rootView.findViewById(R.id.todoItems);
Whenever "this" is used instead use "getActivity()" for example:
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
when using getApplicationContext you must use getActivity().getApplicationContext() for example:
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
in the end my PM_Fragment is altered to look like this:
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
listView = (ListView) rootView.findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) rootView.findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return rootView;
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
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);
}
public void AddItem(View view) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}

Not seeing EditNameDialogListener interface

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

Fragments won't show up in activity extending ActionBarActivity

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();
}
});

How to create a Login task in OnClickListener?

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.

Categories