I am dealing with a problem with compile errors in my java code which I cannot understand how to correct.
First error:
main cannot be resolved or is not a field ....
Second error:
The method OnKeyListener(new MainActivity.OnKeyListener(){}) is undefined for the type EditText
package com.uichat;
import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends Activity{
private ChatArrayAdapter adp;
private ListView list;
private EditText ChatText;
private Button send;
Intent In;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent I = getIntent();
send = (Button) findViewById(R.id.btn);
list = (ListView) findViewById(R.id.list);
adp = new ChatArrayAdapter(getApplicationContext(), R.layout.chat);
ChatText = (EditText) findViewById(R.id.chat);
ChatText.setKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
return sendChatMessage(false);
}
return false;
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
sendChatMessage(false);
}
});
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setAdapter(adp);
adp.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
list.setSelection(adp.getCount() - 1);
}
});
}
private boolean sendChatMessage(boolean side) {
adp.add(new ChatMessage(side, ChatText.getText().toString()));
ChatText.setText("");
side = !side;
return true;
}
public ListView getList() {
return list;
}
public void setList(ListView list) {
this.list = list;
}
class EditView {
private String text;
public void setOnKeyListener(OnKeyListener onKeyListener) {
}
public boolean getText() {
return true;
}
public void setText(String text) {
this.text = text;
}
}
class OnKeyListener {
}
}
First Error:
main cannot be resolved or is not a field ....
setContentView(R.layout.main);
Attempts to reference a non-existent field of R.layout called "main"
It is missing either because you do not have a valid "main.xml" in your res/layout tree, or because you need to clean and rebuild your project to update changes there. (Accidentally importing Android's own R class could do it too, but you haven't done that in your provided code).
Second error:
The method OnKeyListener(new MainActivity.OnKeyListener(){}) is undefined for the type EditText
The method you should be calling for an EditText is setOnKeyListener()
the argument you pass will need to be a class which implements View.onKeyListener
Therefore your internal
class OnKeyListener {
}
Needs to have the required method
class OnKeyListener {
public boolean onKey(View v, int keyCode, KeyEvent event) {
//insert code here
return true;
}
}
see http://developer.android.com/reference/android/view/View.OnKeyListener.html
Related
I am searching Exoplayer using with ViewPager in java but can not find the full tutorial.
I have issue for stopping and pausing exoplayer while swiping another video.
Is there any tutorial please suggest me.
Adapter.java
package com.daasuu.gpuvideoandroid.Adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.daasuu.gpuvideoandroid.Activity.OtherUser.OtherUserProfileActivity;
import com.daasuu.gpuvideoandroid.Model.MainVideoDataModel;
import com.daasuu.gpuvideoandroid.R;
import com.daasuu.gpuvideoandroid.Utils.VideoCache;
import com.daasuu.gpuvideoandroid.databinding.ItemMainVideoBinding;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import java.util.List;
public class MainVideoAdapter2 extends RecyclerView.Adapter<MainVideoAdapter2.MyViewHolder> {
private Context context;
private List<MainVideoDataModel> data;
private boolean likeFlag = false;
private boolean followFlag = false;
private boolean isPlaying = false;
ExoPlayer exoplayer;
StyledPlayerView styledPlayerView;
public MainVideoAdapter2(Context context, List<MainVideoDataModel> data) {
this.context = context;
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemMainVideoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_main_video, parent, false);
return new MyViewHolder(binding);
}
#Override
public void onBindViewHolder(MainVideoAdapter2.MyViewHolder holder, int position) {
MainVideoDataModel model = data.get(position);
holder.setExoplayerStyled(model.getVideo_url());
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemMainVideoBinding binding;
public MyViewHolder(ItemMainVideoBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.imageUserMainVideo.setOnClickListener(this);
binding.videoView.setOnClickListener(this);
}
// styled exoplayer with cache
void setExoplayerStyled(String video_url){
binding.progressCircular.setVisibility(View.VISIBLE);
exoplayer = new ExoPlayer.Builder(context).build();
styledPlayerView = binding.videoStyledPlayerView;
styledPlayerView.hideController();
styledPlayerView.setUseController(false);
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(
new CacheDataSource.Factory()
.setCache(VideoCache.getInstance2(context))
.setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
.setUserAgent("rgcache"))
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(video_url));
exoplayer.seekTo(0);
exoplayer.prepare();
exoplayer.pause();
styledPlayerView.setPlayer(exoplayer);
exoplayer.setPlayWhenReady(false);
binding.videoStyledPlayerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View view) {
styledPlayerView.setKeepScreenOn(true);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().play();
}
}
#Override
public void onViewDetachedFromWindow(View view) {
binding.videoStyledPlayerView.getPlayer().stop();
binding.videoStyledPlayerView.getPlayer().clearMediaItems();
exoplayer.seekTo(0);
exoplayer.setPlayWhenReady(false);
exoplayer.stop();
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().pause();
}
}
});
//buffering
exoplayer.addListener(new Player.Listener() {
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
// Log.e("onIsLoadingChanged", String.valueOf(isLoading));
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
Log.e("onPlaybackStateChanged", String.valueOf(playbackState));
binding.imgVideoStop.setVisibility(View.GONE);
if (playbackState == 3){
binding.progressCircular.setVisibility(View.GONE);
}
}
#Override
public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) {
Player.Listener.super.onPlayWhenReadyChanged(playWhenReady, reason);
}
});
// touch listener play & pause
binding.videoStyledPlayerView.getVideoSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlaying == false){
binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = true;
exoplayer.setPlayWhenReady(false);
}else{
binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = false;
styledPlayerView.setKeepScreenOn(true);
styledPlayerView.setPlayer(exoplayer);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
}
}
});
}
//on click event
#Override
public void onClick(View v) {
if (v == binding.imageUserMainVideo) {
context.startActivity(new Intent(context, OtherUserProfileActivity.class));
}
if (v == binding.videoView) {
Log.e("isPlaying = " , String.valueOf(isPlaying));
if (isPlaying) {
binding.videoView.pause();
// binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = false;
} else {
binding.videoView.start();
// binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = true;
}
}
}
}
}
item.xml
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="#+id/videoStyledPlayerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
app:animation_enabled="true"/>
Issues:
After a specific position, it plays previous videos when swipe to next video.
Plays multiple videos on swipe
On swipe back(previous videos) don't stops previous video.
How to stop when to redirect another activity.
Please suggest the solution.
You can use addOnPageChangeListener for getting the user interaction for the view pager. add this code snippet in the onCreate method.In my project ,I handle it like this ::
binding!!.mediaViewPager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageSelected(position: Int) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageScrollStateChanged(state: Int) {
exoPlayer.pause()
}
})
Play Exo Player With PageViwer
Link:
https://github.com/google/ExoPlayer/issues/7947
Example:
https://github.com/kakajika/PlayerPagerExample
I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I donĀ“t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
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;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.
I'm trying to change the status of a ProgressBar while the user is typing a text on either text fields.
For example , the user starts typing on the first TextView, the ProgressBar should change it's value, if he deletes the text, it should reset to the previous value which is 30
package com.example.phill.jokes;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Entry extends AppCompatActivity {
private ProgressBar pr;
private Handler rHandler = new Handler();
private TextView tv ;
private TextView tv2 ;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
pr = (ProgressBar) findViewById(R.id.progressBar);
tv=(TextView) findViewById(R.id.textView9) ;
tv2=(TextView) findViewById(R.id.textView6) ;
new Thread(new Runnable() {
#Override
public void run() {
while (true)
{
android.os.SystemClock.sleep(300);
rHandler.post(new Runnable() {
#Override
public void run() {
pr.setProgress(30);
if(tv.getText().toString().matches(""))
{
titleboolean=true;
}
else
titleboolean=false;
if(tv2.getText().toString().matches(""))
{
jokeboolean=true;
}
else
jokeboolean=false;
if(titleboolean)
{
pr.setProgress(60);
}
if(jokeboolean)
{
pr.setProgress(100);
}
}
});
if(titleboolean && jokeboolean)
break;
}
rHandler.post(new Runnable() {
#Override
public void run() {
if(titleboolean && jokeboolean){
tv2.setVisibility(View.INVISIBLE);
tv.setVisibility(View.VISIBLE);
}
;
}
});
}
}).start();
}
}
The value of the ProgressBar never changes.
Any Ideas?
Let me explain you in detail
if(titleboolean && jokeboolean)
break;
when your both text fields clears it calls break statement after that your thread stops running you can achieve this in another way
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ProgressBar;
import android.widget.TextView;
public class TestActivity extends AppCompatActivity
{
private ProgressBar pr;
private EditText tv;
private EditText tv2;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pr=(ProgressBar)findViewById(R.id.progressBar);
tv = (EditText) findViewById(R.id.tv);
tv2 = (EditText) findViewById(R.id.tv2);
TextView tV = new TextView(this);
tV.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
tv2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
}
public void setProgress() {
pr.setProgress(30);
if (tv.getText().toString().matches("")) {
titleboolean = true;
} else
titleboolean = false;
if (tv2.getText().toString().matches("")) {
jokeboolean = true;
} else
jokeboolean = false;
if (titleboolean) {
pr.setProgress(60);
}
if (jokeboolean) {
pr.setProgress(100);
}
}
}
Use EditText instead TextView with TextChangedListener.
TextView does not allow to type text.
Also infinite cycle with pauses is bad approach, use EditText.addTextChangedListener to handle text after it have changed
We want to call list view 'm_vwList' in another class, so that when check out button (in another class) is pressed, the list is cleared from Quick Order Class.
Can someone pls tell how to call the list view in another class and then clear it after clicking the button. we know the button functionality but not sure of how to clear the list
package com.zing.basket;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
/**
* Created by Student on 18/03/2016.
*/
public class QuickOrder extends android.support.v4.app.Fragment implements View.OnClickListener, View.OnKeyListener {
private EditText m_vwEditText;
private Button m_vwButton;
private ListView m_vwList;
private ArrayAdapter<String> m_adapter;
View myFragmentView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment_quickorder, container, false);
m_vwEditText = (EditText) myFragmentView.findViewById(R.id.editText);
m_vwButton = (Button) myFragmentView.findViewById(R.id.button);
m_vwList = (ListView) myFragmentView.findViewById(R.id.list);
m_adapter = new ArrayAdapter<String>(getActivity(), R.layout.textview);
String[] listItems = getResources().getStringArray(R.array.listitems);
for (String item : listItems) {
m_adapter.add(item);
}
m_vwList.setAdapter(m_adapter);
m_vwButton.setOnClickListener(this);
m_vwEditText.setOnKeyListener(this);
return myFragmentView;
}
/** Called when the Button is clicked */
public void onClick(View v) {
String item = m_vwEditText.getText().toString();
m_vwEditText.setText("");
if (!item.equals("")) m_adapter.add(item);
}
/** Called whena key is pressed while the EditText view has focus */
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
String item = m_vwEditText.getText().toString();
m_vwEditText.setText("");
if (!item.equals("")) m_adapter.add(item);
}
return true;
}
return false;
}
}
To call ListView of a different class, you need to get instance of that class and check it's null or not. Fore more look at:
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().mDrawerList.invalidateViews();
}
I am quite new to programming Android (7 months), and I am having a problem with creating an app.
What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me?
Here is my Main Activity code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}
private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);
}
#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, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
My EditData activity code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}
private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_menu, 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);
}
}
And my Parcelable class used for transferring data values:
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;
public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}
public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}
public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
public int getPersonHeight() {
return personHeight;
}
public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}
public int getPersonWeight() {
return personWeight;
}
public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}
public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P
You shouldn't start variable names with capital letters. Your button MainActivity is very confusing. Better name it something like btMainActivity or something like that.
It think your problem is, that you forget to put an extra to your MainActivity, like you did when starting EditData:
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
// put your extra here
EditData.this.startActivity(EditActivity);
}
});
For what you want, you could also use startActivityForResult. Take a look at it! You should also check out AndroidAnnotations. It can safe you a lot of code and time. I can't imagine making an Android app without it anymore.