Android - Buttons: Receiving through data through intents/other methods - java

E/AndroidRuntime(15518): FATAL EXCEPTION: main
E/AndroidRuntime(15518): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cydeon.plasmamodz/com.cydeon.plasmamodz.Boots}: java.lang.NullPointerException
E/AndroidRuntime(15518): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
E/AndroidRuntime(15518): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
E/AndroidRuntime(15518): at android.app.ActivityThread.access$600(ActivityThread.java:154)
E/AndroidRuntime(15518): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
E/AndroidRuntime(15518): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(15518): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(15518): at android.app.ActivityThread.main(ActivityThread.java:5235)
E/AndroidRuntime(15518): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(15518): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(15518): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
E/AndroidRuntime(15518): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
E/AndroidRuntime(15518): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(15518): Caused by: java.lang.NullPointerException
E/AndroidRuntime(15518): at android.app.Activity.findViewById(Activity.java:1839)
E/AndroidRuntime(15518): at com.cydeon.plasmamodz.Boots.<init>(Boots.java:47)
E/AndroidRuntime(15518): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(15518): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime(15518): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
E/AndroidRuntime(15518): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
E/AndroidRuntime(15518): ... 11 more
The topic is confusing. Let me explain. In my app, I have over 70 buttons just for one section. I have many different sections. Now, each button uses the same layout, so each button starts the same activity, that way I don't create 70 seperate classes. Now, in this new class, it must show an image and download a file(when a certain button is clicked) corresponding to the bugton that was picked. So, basically, I need some way to identify those buttons in this other class, and say "if button x was pressed, display image y, if button y was pressed, display image x. Similarly, if button x was pressed, download file y, if button y was pressed, downloa d file x, ect. I just have no idea how to tell which button was pressed in that previous class. I really need help with this. I've been working for 2 weeks and this has put me to a stop, and I cannot find an answer. This isn't really code dependent, and I'll be using this method multiple times throughout the app, so I don't think posting any code is needed. Again, to reiterate my question, multiple buttons start the same activity. In that activity, I need to do stuff according to the button that was pressed in the previous class. Thanks. :)
Edit: Here's some code...
BootFragment.java:
package com.cydeon.plasmamodz;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.stericson.RootTools.RootTools;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class BootFragment extends Fragment {{
//Defining File Directory
File directory = new File(Environment.getExternalStorageDirectory() + "/plasma/boot");
if(directory.exists() && directory.isDirectory()){
//Do nothing. Directory is existent
}else{
//Directory does not exist. Make directory (First time app users)
directory.mkdirs();
}
File bkup = new File(Environment.getExternalStorageDirectory() + "/plasma/boot/bkup");
if(bkup.exists() && bkup.isDirectory()){
//Do nothing. Directory is existent
}else{
//Directory does not exist. Make directory (First time app users)
bkup.mkdirs();
}}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.boot_frag,
container, false);
Button Ablue = (Button) view.findViewById(R.id.bABlue);
Button AblueR = (Button) view.findViewById(R.id.bABlueR);
Button Abokeh = (Button) view.findViewById(R.id.bAbokeh);
Ablue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent b = new Intent(getActivity(), Boots.class);
b.putExtra("Dragon", R.id.bABlue);
BootFragment.this.startActivity(b);
}
});
AblueR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent c = new Intent(getActivity(), Boots.class);
c.putExtra("Xbox", R.id.bABlueR);
BootFragment.this.startActivity(c);
}
});
Abokeh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent d = new Intent(getActivity(), Boots.class);
d.putExtra("GameB", R.id.bAbokeh);
BootFragment.this.startActivity(d);
}
});
return view;
}}
Boots.java:
package com.cydeon.plasmamodz;
import com.stericson.RootTools.*;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.TimeoutException;
import com.cydeon.plasmamodz.R;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
//Class for Boot Animation Blue Kindle
public class Boots extends Activity {
public static String TAG = "Boots";
Process process;
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... sURL) {
try{
URL url = new URL(sURL[0]);
URLConnection connection = url.openConnection();
connection.connect();
//Shows 0-100% progress bar
int fileLength = connection.getContentLength();
//Download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/plasma/boot/b..ootanimation.zip");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
//Publish the Progress
publishProgress((int) (total * 100/fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress){
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
Context context = getApplicationContext();
CharSequence text = "Installing. Please Wait";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (RootTools.isBusyboxAvailable()){
RootTools.remount("/system", "rw");
CommandCapture command = new CommandCapture(0, "su", "sh /sdcard/plasma/scripts/boots.sh");
try {
RootTools.getShell(true).add(command).waitForFinish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
} else {
RootTools.offerBusyBox(Boots.this);
}
}
}
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boots);
ActionBar actionBar = getActionBar();
actionBar.hide();
ImageView img = (ImageView) findViewById(R.id.iv2);
img.setImageResource(R.drawable.boot1);
Button install = (Button) findViewById(R.id.bAInstall);
Button rtrn = (Button) findViewById(R.id.bAReturn);
mProgressDialog = new ProgressDialog(Boots.this);
mProgressDialog.setMessage("Downloading..." );
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
install.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
TextView creator = (TextView) findViewById(R.id.tvCreate);
Intent bootI = getIntent();
int dball = getIntent().getExtras().getInt("Dragon", -1);
int xbox = getIntent().getExtras().getInt("Xbox", -1);
int GameB = getIntent().getExtras().getInt("GameB", 1);
if (dball != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("Dragon Ball");
}if (xbox != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("Xbox");
}if (GameB != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("GameBoy");
}
}
}
);
rtrn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
}
}
I have tried many different methods. This is my latest attempt. None of them have worked.
Cat log: Look at the top...

Pass the required information to the new activity in the Intent, via Intent.putExtra()
(see http://developer.android.com/reference/android/content/Intent.html)

You may try assigning each button a unique name/id. When the Button is clicked, retrieve its name and pass it to the new activity using Intent.putExtra(). In new activity, once you have this information, you can perform required function accordingly.
Sample Code :
In the xml for Button, do this
android:onClick="OnButtonClick"
In code of First Activity, defineOnButtonClick as :
public void OnButtonClick(View v) {
switch (v.getId()) {
case R.id.button1:
doSomething1(); //Intent.putExtra(ButtonID)
break;
case R.id.button2:
doSomething2();
break;
}
}
In second Activity, retrieve this ID and have a similar switch-case to perform actions depending on Id of Button.
Hope this makes sense!

In Your fragment class, do the following :
public class BootFragment extends Fragment implements android.view.View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Button Ablue = (Button) view.findViewById(R.id.bABlue);
Button AblueR = (Button) view.findViewById(R.id.bABlueR);
Button Abokeh = (Button) view.findViewById(R.id.bAbokeh);
Ablue.setOnClickListener(this);
AblueR.setOnClickListener(this);
Abokeh.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int btnId = v.getId();
Intent d = new Intent(getActivity(), Boots.class);
d.putExtra("BUTTON_ID", btnId);
startActivity(d);
}
}
In Boots.java, do the following:
public class Boots extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
int btnId = getIntent().getExtras().getInt("BUTTON_ID", -1);
switch(btnId){
case: R.id.your_btn_id_1:
// logic for your button press
break;
case: R.id.your_btn_id_2:
// logic for your button press
break;
case: R.id.your_btn_id_n:
// logic for your button press
break;
}
}
}
Note: You should provide unique id to each button in layout xml file

Related

Getting the button press on recycler view item which is created with method

I'm pretty new to Android Studio and Java overall so this might be simple question but I couldn't find any solutions or either couldn't use them to fix my issue.
So I have a RecyclerView which I can insert items from a list of pre-defined items with the function "addItems()" when I press to a button and display them.
Also those items have ImageButtons -which is just a transparent rectangle- to get individual clicks on them.
The purpose of these ImageButtons are to switch to a new activity which I defined in the "addItems()" method.
But the problem is, I can't catch -but they respond to the clicks- click on those items, and also I can't pass the activity class or the layout file.
To be exact, I want to use these buttons to switch to a new activity and display the info of that item there.
It's my first question here, so if I need to show any code, please tell me to.
NewsAdapter.java
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder>
{
Context mContext;
List<NewsItem> mData;
public NewsAdapter(Context mContext, List<NewsItem> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View layout;
layout = LayoutInflater.from(mContext).inflate(R.layout.lyt_restoran,viewGroup,false);
return new NewsViewHolder(layout);
}
// Changed below ----------
#Override
public void onBindViewHolder(#NonNull NewsViewHolder newsViewHolder, int position) {
// Bind data here
newsViewHolder.tvSellerName.setText(mData.get(position).getSellerName());
newsViewHolder.tvSellerAddress.setText(mData.get(position).getSellerAddress());
newsViewHolder.ivSellerImage.setImageResource(mData.get(position).getSellerImage());
newsViewHolder.tvMinCost.setText(mData.get(position).getMinCost());
newsViewHolder.tvMinTime.setText(mData.get(position).getMinTime());
newsViewHolder.tvDeliveryCost.setText(mData.get(position).getDeliveryCost());
newsViewHolder.tvClassToGo.setText(mData.get(position).getClassToGo());
// Line below is the buttons attached to the items which I aim to use on switching Activities
newsViewHolder.ibGoSellerPage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(SiparisActivity.this, classDominos.class);
startActivity(intent); // startActivity is marked red
}
});
}
// Changed above ----------
#Override
public int getItemCount() {
return mData.size();
}
public class NewsViewHolder extends RecyclerView.ViewHolder{
TextView tvSellerName, tvSellerAddress, tvMinCost, tvMinTime, tvDeliveryCost, tvClassToGo;
ImageView ivSellerImage;
ImageButton ibGoSellerPage;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
tvSellerName = itemView.findViewById(R.id.tvFoodName);
tvSellerAddress = itemView.findViewById(R.id.tvFoodDescription);
ivSellerImage = itemView.findViewById(R.id.ivFoodImage);
tvMinCost = itemView.findViewById(R.id.tvFoodCost);
tvMinTime = itemView.findViewById(R.id.tvMinTime);
tvDeliveryCost = itemView.findViewById(R.id.tvDeliveryCost);
tvClassToGo = itemView.findViewById(R.id.tvClassToGo);
ibGoSellerPage = itemView.findViewById(R.id.ibGoSellerPage);
//int position = getAdapterPosition();
//Toast.makeText(mContext.getApplicationContext(), "Position is: "+position, Toast.LENGTH_SHORT).show();
}
}
}
SiparisActivity.java //this is where I list restaurant items with ImageButtons said above.
package com.example.yiyecek2.Activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.yiyecek2.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import recyclerview.CustomItemAnimator;
public class SiparisActivity extends AppCompatActivity {
Button btnListRestaurants;
RecyclerView NewsRecyclerView;
NewsAdapter newsAdapter;
List<NewsItem> mData;
ImageButton ibGoSellerPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_siparis);
// Hide the action bar
getSupportActionBar().hide();
NewsRecyclerView = findViewById(R.id.news_rv);
btnListRestaurants = (Button) findViewById(R.id.buttonListRestaurants);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
NewsRecyclerView.setHasFixedSize(true);
NewsRecyclerView.setItemAnimator(new CustomItemAnimator());
// Get clicks on the "List Restaurants"
btnListRestaurants.setOnClickListener(new View.OnClickListener() {
int restaurantCount = 0;
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getApplicationContext(), "Listing Restaurants", Toast.LENGTH_SHORT);
toast.show();
Timer timerToTransition;
timerToTransition = new Timer();
TimerTask task = new TimerTask() {
public void run() {
addItems();
restaurantCount++;
if (restaurantCount > 9)
{
System.out.println(restaurantCount);
timerToTransition.cancel(); // Stops the timer when theres 10 Restaurants listed
}
}
};
timerToTransition.scheduleAtFixedRate(task,0,300); // waits 300ms before creating a new Restaurant
}
});
if (ibGoSellerPage != null) // Check if Restaurant button exists
{
System.out.println("ON CLICK HERE");
ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
}
mData = new ArrayList<>();
// fill list news with pre defined data
// Adapter ini and setup
newsAdapter = new NewsAdapter(this,mData);
NewsRecyclerView.setAdapter(newsAdapter);
NewsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void addItems()
{
RecyclerView.State state = null;
int switchInt = 0; // To use in the switch
// Random integer list to assign switchInt a random value
int[] intList;
intList = new int[]{0,1,2,3,4,5,6,7};
// Pick a random int
Random rand = new Random();
int rndInt = rand.nextInt(5);
// Check if the array's index isn't empty(-1)
while (intList[rndInt] != -1)
{
switchInt = (int) intList[rndInt];
intList[rndInt] = -1;
}
//System.out.println(rndInt);
switch(switchInt) {
case 0:
mData.add(0,new NewsItem("Domino's Pizza","Sarıgöl, Ordu Cd. No:128, 34240 Gaziosmanpaşa/İstanbul",
R.drawable.dominos,"32 TL","30 dk.","0 TL","classDominos")); // I'm trying to catch that "classDominos" to use to switch Activity
break;
case 1:
mData.add(0,new NewsItem("Migros","Bağlarbaşı, Küçükköy Yolu Cd., 34245 Gaziosmanpaşa/İstanbul",
R.drawable.migroslogo,"32 TL","25 dk.","0 TL", "classDominos"));
break;
case 2:
mData.add(0,new NewsItem("KFC","Yeşilpınar Mah. Şehit Metinkaya Sok Vialand AVM No:11 Mağaza No:237, 34065 Eyüpsultan",
R.drawable.kfclogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 3:
mData.add(0,new NewsItem("Popeyes","Yeşilpınar Mah. Şehit Metin Kaya Sok. No:11 K:3 Vialand AVM, 34065",
R.drawable.popeyeslogo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
case 4:
mData.add(0,new NewsItem("Mado","İslambey, Hz. Halid Blv. No:43 D:B, 34050 Eyüpsultan/İstanbul",
R.drawable.madologo,"32 TL","35 dk.","3 TL", "classDominos"));
break;
default:
break;
}
System.out.println("Added item");
newsAdapter.notifyItemInserted(0);
NewsRecyclerView.getLayoutManager().smoothScrollToPosition(NewsRecyclerView, state, 0);
// Un-commenting the lines below crash the app when "Listing Restaurants" (Creating items)
//ibGoSellerPage = (ImageButton) findViewById(R.id.ibGoSellerPage);
/*ibGoSellerPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("ON CLICK HERE");
}
});
*/
}
}
I can see the individual buttons in the profiler but how to catch clicks on them? (You can see I'm holding the button on the right)
Profiler Screenshot
I think the problem with you is that the click event happen on the screen in another view
By making a transparent rectangle i think the click go to the parent view
Try to test that for ex:
<LinearLayout
android:id="#+id/layout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
handle the click on layout view if it work so you need to change the transparent rectangle button to a bold one or another approach
better to add some code from your side to help us understand the problem well

Error occuring in my Java/Android code on import line

I am really new to Android Studio, and am trying to get up to speed. I got some code from the web and I have an errors I know it is because I am referencing a package that is not in my project but how could I resolve this.
The line that has the error is:
import com.androidmkab.randomsplash.MainActivity;
and this is the full code.
package org.quaestio.kotlinconvertedwebview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.ImageView;
import com.androidmkab.randomsplash.MainActivity;
import java.util.Random;
public class Splashscreen extends Activity {
Thread splashTread;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
imageView = (ImageView)findViewById(R.id.imageView2);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
int[] ids = new int[]{R.drawable.s_img,R.drawable.s_image_black, R.drawable.s_image_black2};
Random randomGenerator = new Random();
int r= randomGenerator.nextInt(ids.length);
this.imageView.setImageDrawable(getResources().getDrawable(ids[r]));
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
Intent intent = new Intent(Splashscreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
Splashscreen.this.finish();
} catch (InterruptedException e) {
// do nothing
} finally {
Splashscreen.this.finish();
}
}
};
splashTread.start();
}
}
So import com.androidmkab.randomsplash.MainActivity means where the MainActivity is located, you need to replace that package with your own. To do this copy your package name(in the top of your activity) and add the activity you want to import, in this case MainActivity.java: import org.quaestio.kotlinconvertedwebview.MainActivity;
Hope it was helpful.

Buttons onClick method restarts if clicked to fast

I have little application where you can tell your fortune (it's actualy just random), there are four edittextfields that you can type in and one button that choose one of the edittextfields, and remove it. Pretty simple. But i have problem, if someone presses the button multiple times too fast then all of the code in the onClick() method doesn't execute (probably because it is called again). Is there some way that I can prevent this from happening (I want all of the code in the onClick() method to execute before it can be called again)?
Here is the code:
package com.foretell.lukas.spamedprick;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
ArrayList<EditText> tfa = new ArrayList<EditText>();
int x = 0;
boolean tf = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// References to XML widgets
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.background);
final Button daButton = (Button) findViewById(R.id.button);
Button restartButton = (Button) findViewById(R.id.restartButton);
final EditText ruta1 = (EditText) findViewById(R.id.editText);
final EditText ruta2 = (EditText) findViewById(R.id.editText2);
final EditText ruta3 = (EditText) findViewById(R.id.editText3);
final EditText ruta4 = (EditText) findViewById(R.id.editText4);
final TextView outputText = (TextView) findViewById(R.id.outputText);
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.spar);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hurra);
daButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
if(tf) {
daButton.setEnabled(false);
mp.start();
try {
tf = false;
Thread.sleep(2000);
} catch (InterruptedException e) {
e.getStackTrace();
outputText.setText("Nått gick åt h***ete!");
}
Collections.shuffle(tfa);
x++;
if (x <= 2) {
outputText.setText("Det är inte " + tfa.get(0).getText() + "...");
tfa.get(0).setText("");
tfa.remove(0);
} else if (x == 3) {
outputText.setText("Det är...");
} else if (x == 4) {
tfa.get(1).setText("");
tfa.remove(1);
outputText.setText("Det är " + tfa.get(0).getText() + "!");
mp2.start();
}
tf = true;
daButton.setEnabled(true);
}else{
System.out.println("YO!");
}
}
}
);
restartButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
ruta1.requestFocus();
outputText.setText("");
x = 0;
ruta1.setText("");
ruta2.setText("");
ruta3.setText("");
ruta4.setText("");
}
}
);
}
}
Thanks.
I dont think that an "onClick" can be started before the last "onClick" is finished.
Here is the qoute from the android documentation:
The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.
http://developer.android.com/guide/components/processes-and-threads.html
Maybe you do something in the onClick method, that makes trouble, but without the code it is hard to tell:)
You have to do something like this
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button.setEnabled(false);
// do your work here
// make it true after your work is done
button.setEnabled(true);
}
});

read from file in android using assets

I am trying to read file from assets in android. I want every button to print a paragraph, for example the first button prints the first paragraph and the second button print the second paragraph.
I tried with the code below but its not working.
I get this error message:
03-03 18:40:17.800: E/AndroidRuntime(977): FATAL EXCEPTION: main
03-03 18:40:17.800: E/AndroidRuntime(977): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.hajjapp.AfterHajj }
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1622)
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
03-03 18:40:17.800: E/AndroidRuntime(977): at android.app.Activity.startActivityForResult(Activity.java:3370) –
Can anyone tell me where the problem is?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Dialog;
import android.content.res.AssetManager;
public class BeforeHajj extends ActionBarActivity {
Button whatHajj;
TextView text;
Button hajjTime;
String before;
String [] s;
String timeHajj="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_before_hajj);
whatHajj = (Button)findViewById(R.id.whatisHajj);
hajjTime = (Button)findViewById(R.id.hajjTime);
text = (TextView)findViewById(R.id.text);
whatHajj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try
{
AssetManager assetmanager=getAssets();
InputStream input=assetmanager.open("beforehaj.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(input));
String st="";
StringBuilder sb=new StringBuilder();
while((st=br.readLine())!=null)
{
sb.append(st);
before+=sb.toString();
s=before.split("*");
}
text.setText(before);
}
catch(IOException ep) {
text.append(ep.toString());
}
}
});
hajjTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// custom dialog
try
{
AssetManager assetmanager=getAssets();
InputStream input=assetmanager.open("beforehaj.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(input));
String st="";
StringBuilder sb=new StringBuilder();
while((st=br.readLine())!=null){
sb.append(st);
before+=sb.toString();
s=before.split("*");
}
}
catch(IOException ep) {
text.append(ep.toString());
}
final Dialog dialog = new Dialog(BeforeHajj.this);
dialog.setContentView(R.layout.guide_dialog);
dialog.setTitle("Hajj Time");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
text.append(s[0]);
ImageView image = (ImageView) dialog.findViewById(R.id.dialog_image);
image.setImageResource(R.drawable.dolheja);
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_button);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.before_hajj, 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);
}
}
Somewhere, you are trying to start an activity that is supposed to be implemented in the Java class com.example.hajjapp.AfterHajj. The error message is telling you that there is no <activity> element in the manifest for this class. Also note that the code you pasted into your question is from a Java class named BeforeHajj.
Use new line character to split the paragraphs. All paragraphs start with a new line, so use
before.split("\\\n");
This shall do the job for you.
Use escape symbols to make the '*' be recognized by split, e.g. s.split("\\*");

I want to make password protected android application

I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.

Categories