I am trying to follow a tutorial and have got stuck with what I figure to be the last error before completion.
Can someone tell me what I am doing wrong with these variables?
Including both activities below, if any other code is applicable, I am happy to provide it.
Error codes read:
Error:(21, 56) error: cannot find symbol variable pickupLine
Error:(24, 9) error: cannot find symbol variable retryButton
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
MainActivity.java:
package io.wavey.pickuplesson1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Grab clean button so we can do stuff with it!
Button cleanButton = (Button) findViewById(R.id.cleanButton);
final Button dirtyButton = (Button) findViewById(R.id.dirtyButton);
final String pickupLine = "You had me at hello world";
//This is a Callback.
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendLine(pickupLine);
}
});
}
//Send to activity
private void sendLine(String pickupLine) {
Intent intent = new Intent(this, LineActivity.class);
intent.putExtra("Pickup Line", pickupLine);
startActivity(intent);
}
}
LineActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line);
Bundle pickupData = getIntent().getExtras();
if (pickupData == null) {
return;
}
String receivedPickupLine = pickupData.getString("Pickup Line");
TextView newLine = (TextView) findViewById(R.id.pickupLine);
newLine.setText(receivedPickupLine);
retryButton.setOnClicklistener (new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
LineActivity.java:
Related
We have programmed a chat application with Firebase in which the sender's messages are to be displayed on the right and those of the recipient on the left side.
The sender's messages are correctly displayed on the right side if you send the message with the Send button.
Unfortunately, the messages to the receiver are not shown on the left side.
Our Recyclerview java Code is this one:
package com.example.myapplicationsonet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Message_recyclerview extends AppCompatActivity {
TextView tvUsername;
ImageButton ibtnSend;
EditText etMessage;
FirebaseUser fuser;
DatabaseReference databaseReference;
MessageAdapter messageAdapter;
List<message_helperclass> mChat;
RecyclerView recyclerView;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_message_recyclerview );
recyclerView = (RecyclerView) findViewById(R.id.rvmessage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
tvUsername = (TextView) findViewById(R.id.textView_message_username);
etMessage = (EditText) findViewById(R.id.messagebox);
ibtnSend = (ImageButton) findViewById(R.id.button_send);
intent = getIntent();
final String username = intent.getStringExtra("username");
fuser = FirebaseAuth.getInstance().getCurrentUser();
fuser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(username);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
tvUsername.setText(username);
readMessages(fuser.getUid(), username);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ibtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMessage.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), username, msg);
}else {
Toast.makeText(Message_recyclerview.this, "Du kannst keine leeren Nachrichten versenden", Toast.LENGTH_LONG).show();
}
etMessage.setText("");
}
});
}
private void sendMessage(String sender, String receiver, String message ){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
databaseReference.child("Chats").push().setValue(hashMap);
}
private void readMessages(final String myid, final String username){
mChat = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
message_helperclass chat = snapshot.getValue(message_helperclass.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(username) ||
chat.getReceiver().equals(username) && chat.getSender().equals(myid)){
mChat.add(chat);
}
messageAdapter = new MessageAdapter(Message_recyclerview.this, mChat);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And this is our Adapter Class:
package com.example.myapplicationsonet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<message_helperclass> mChat;
FirebaseUser fUser;
public MessageAdapter(Context mContext, List<message_helperclass> mChat){
this.mChat = mChat;
this.mContext = mContext;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
message_helperclass chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
}
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fUser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
Unfortunately, we cannot find the error why the recipient messages are not displayed on the left.
I hope you can help us. It would be important.
Thanks!
Can't Comment, but have you checked your chat_item_right and chat_item_left XML file? Your code appears right so the error might be there.
I have a problem on up back icon toolbar, when i click twice to go back app crash on nullpointer exception recalling the error on my getActivity().onBackPressed();
this is the fragment:
package com.example.android.evilsecretgallery;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
public class ImageDetailFragment extends Fragment {
private static final String EXTRA_IMAGE = "image_item";
private static final String EXTRA_TRANSITION_NAME = "transition_name";
public ImageDetailFragment() {
// Required empty public constructor
}
public static ImageDetailFragment newInstance(ImageModel image, String transitionName) {
ImageDetailFragment fragment = new ImageDetailFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_IMAGE, image);
args.putString(EXTRA_TRANSITION_NAME, transitionName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postponeEnterTransition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(getActivity(), R.style.EvilTextAppearance);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageModel image = getArguments().getParcelable(EXTRA_IMAGE);
String transitionName = getArguments().getString(EXTRA_TRANSITION_NAME);
final PhotoView imageView = view.findViewById(R.id.detail_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setTransitionName(transitionName);
}
Glide.with(getActivity())
.asBitmap()
.load(image.getUrl())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
startPostponedEnterTransition();
imageView.setImageBitmap(resource);
}
});
}
}
that go back in this activity:
package com.example.android.evilsecretgallery;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class PagesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
then if I go back again to this activity below it gives me the error:
package com.example.android.evilsecretgallery;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView cover;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
cover = findViewById(R.id.cover_id);
cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new intent to open the PagesActivity
Intent intent = new Intent(MainActivity.this, PagesActivity.class);
// Start the new activity
startActivity(intent);
}
});
Button siteButton = findViewById(R.id.site_button);
siteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://www.evilsecret.it";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
I have made some experiment and if i go back from pages activity it has no problem. I have to use different method in the fragment?
try clean and rebuild your project
It worked for me.
I am stuck when learning handlers. The following is my simple code:
public class MainActivity extends AppCompatActivity {
Thread thread;
public Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
thread = new Thread(new MyThread());
thread.start();
handler=new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
}
class MyThread implements Runnable{
#Override
public void run(){
Message message=Message.obtain();
for(int i=0;i<10000;i++){
handler.sendMessage(message);
}
}
}
}
In the MyThread class, i was trying to type sendMessage after handler. but android studio does not show any such sendMessage option. still i typed it, then it shows in red. and says cannot resolve method.
You have imported wrong handler class
import java.util.logging.Handler;
And sendMessage method does not belong to this class
Try this import android.os.Handler;
Example:
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
Thread thread;
Handler handler;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressbar = (ProgressBar) findViewById(R.id.progressbar1);
thread = new Thread(new MyThread());
thread.start();
handler = new Handler() {
public void handleMessage(Message msg) {
progressbar.setProgress(msg.arg1);
};
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
class MyThread implements Runnable {
#Override
public void run() {
Message message = Message.obtain();
Log.d("message", "" + message);
for (int i = 0; i < 100; i++) {
message.arg1 = i;
handler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
I know that i am probably missing something simple but i am getting this error when i try to load my second activity and i have no idea why, I understand (Or iv'e been told) That it happens when your code doesn't point to anything, But iv'e checked it and it points to the correct location.
ResultText
package com.example.mdpmk1;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ResultText extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addListenerOnButton();
//Points /\
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.returnHome);
button.setOnClickListener(new OnClickListener() {
//Points /\
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
});
String result=getIntent().getStringExtra("resultText");
setContentView(R.layout.result_text);
TextView tv=new TextView(this);
tv.setTextSize(20);
String str=result;
tv.setText(str);
setContentView(tv);
}
}
If you require any more of the files feel free to ask.
Sorry if its a noob question and thanks for the help in advance.
call setContentView(R.layout.result_text); before calling addListenerOnButton();
Like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_text);
addListenerOnButton();
}
I'm new in android programming. My first application is an android mediaplayer.
I built two buttons : one to play a song, and another to stop it.
My application is running correctly ; the problem is that i can play and stop it, but I cant play the song again.
I tried to use setDataSource() but it triggers an error.
Here's the code ; the file is in raw/song.mp3
package com.example.test6;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(this,R.raw.song);
setContentView(R.layout.activity_main);
final Button btnPlay = (Button)this.findViewById(R.id.button1);
final Button btnStop = (Button)this.findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mp.start();
}
});
btnStop.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mp.stop();
mp.reset();
if(mp.isPlaying()){
mp.stop();
}else{
mp.setDataSource("res/raw/song.mp3");
mp.prepare();
mp.start();
}
});
}
}
First of all, you don't need to set the data source manually if you're doing the creation like this: MediaPlayer.create(this, R.raw.song); Also, in that case, you don't need to call prepare() because MediaPlayer.create() does that for you.
I would suggest this kind of approach (assuming you don't want the start button to do anything if it's already playing):
Start button listener:
if (mp==null) {
mp = MediaPlayer.create(this, R.raw.song);
}
if (!mp.isPlaying()) {
mp.start();
}
Stop button listener:
if (mp!=null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
I didn't test this, so I'm looking forward to your response