android activity work with intent - java

i made three activities for a game i want to go from 1st to 2nd to 3rd and then go 1st 2nd 3rd again but i got confused with the whole intent thing tried all kind of combinations but for some reason i stuck always with a problem currently it goes from 1st to 2nd to 3rd to 1st and when it supposed to lunch 2nd it exits from the whole app
//1st activity
Intent discoverintent = new Intent(getBaseContext(), discoverstring.class);
//discoverintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(discoverintent);
//2nd activity
Intent MainIntent = new Intent(getBaseContext(), learningword.class);
//MainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("text", text);
MainIntent.putExtra("speakeronoff", Integer.toString(speakeronoff));
MainIntent.putExtra("previous", Integer.toString(previous));
startActivity(MainIntent);
and the 3rd activity just uses finish
package self.yanfaingold.talkgame;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
#SuppressLint("NewApi") public class savewords extends Activity implements OnTouchListener {
OurView v;
//Intent secondintent;
Canvas c;
int cheight,cwidth,loop=0;
Bitmap notalk,notalkscaled,bittalk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
//Remove title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(v);
notalk=BitmapFactory.decodeResource(getResources(), R.drawable.nottalk);
// bittalk=BitmapFactory.decodeResource(getResources(), R.drawable.talkmid);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t=null;
SurfaceHolder holder;
boolean isItOK=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run(){
while(isItOK){
if(!holder.getSurface().isValid()){
continue;
}
c=holder.lockCanvas();
cheight=c.getHeight();
cwidth=c.getWidth();
scale();
drawing(c);
holder.unlockCanvasAndPost(c);
}
}
private void scale() {
// TODO Auto-generated method stub
if(loop==0)
notalkscaled=Bitmap.createScaledBitmap(notalk,(int)(cwidth),(int)(cheight), false);
}
protected void drawing(Canvas canvas){
//canvas.drawARGB(255, 255, 255, 255);
canvas.drawBitmap(notalkscaled,0,0, null);
if(loop>500){
loop=0;
wannalearnaword();
}
loop++;
}
private void wannalearnaword() {
// TODO Auto-generated method stub
//1st activity
Intent secondintent = new Intent(getApplicationContext(), discoverstring.class);
secondintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(secondintent);
}
public void pause(){
isItOK=false;
while(true){
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
t=null;
}
public void resume(){
isItOK=true;
t=new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
}

Related

Android thread test does not work

Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.

why is the below code force closes on using built in camera in android project?

package com.example.thenewjay;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener {
ImageView iv;
Button but;
ImageButton ib;
final static int cameraData = 0;
Intent i;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
initialize();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void initialize() {
iv = (ImageView) findViewById(R.id.ivReturnedPic);
ib = (ImageButton) findViewById(R.id.ibTakePic);
but = (Button) findViewById(R.id.bSetWall);
but.setOnClickListener(this);
ib.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibTakePic:
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 1);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}}
}
why is the below code force closes on using built in camera in android
project?
Because you are missing setContentView in onCreate before calling initialize().
You will need to set layout for current Activity before calling findViewById to access views from current screen xml.do it as in onCreate:
...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_name);
initialize();
....

how to display alert dialog box in button if target action fails

I am trying to create an app where the user can take a photo and set it as wallpaper.Now when i click the button and get back without taking a photo and click set wallpaper i want to display an alert dialog box.I have been able to set it when the image capture is not initiated but not when initiated but no image is taken
package com.sagarapp;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener{
ImageView img;
ImageButton takepic;
Button setdp;
Intent i;
final static int cameraData = 0;
Bitmap bmp;
final Context context = this;
boolean taken = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
initialize();
takepic.setOnClickListener(this);
setdp.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
img = (ImageView)findViewById(R.id.Ivpic);
takepic = (ImageButton)findViewById(R.id.Ibcapture);
setdp = (Button)findViewById(R.id.Bsetdp);
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.Ibcapture:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
taken = true;
startActivityForResult(i,cameraData);
break;
case R.id.Bsetdp:
try {
if(taken)
getApplicationContext().setWallpaper(bmp);
else{
AlertDialog.Builder alertDialogBulider = new AlerDialog.Builder(context);
alertDialogBulider.setTitle("Warning!");
alertDialogBulider.setMessage("No Image Is Available");
alertDialogBulider.setCancelable(false);
alertDialogBulider.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBulider.create();
alertDialog.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
bmp = (Bitmap)extras.get("data");
img.setImageBitmap(bmp);
}
else
{
AlertDialog.Builder alertDialogBulider = new AlertDialog.Builder(context);
alertDialogBulider.setTitle("Warning!");
alertDialogBulider.setMessage("No Photo Is Taken");
alertDialogBulider.setCancelable(false);
alertDialogBulider.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBulider.create();
alertDialog.show();
}
}
}
Your taken boolean variable should only be set to true if you receive a RESULT_OK resultcode in onActivityResult() method. That means that the user actually took a picture and saved it. Remove it from the R.id.Ibcapture View onClick () method.

Error in NSD Network Service Discovery in android

I don't know whats going wrong with my app i followed so many tutorials, any hint/help/advise would be appreciated, I am new on android. i am getting error as in onserviceregistrationfailed function of listner.
package com.example.ravinetworkapplication;
import java.io.IOException;
import java.net.ServerSocket;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.pm.ServiceInfo;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
NsdManager mNsdManager;
Context context;
NsdManager.DiscoveryListener mDiscoveryListner=null;
NsdManager.RegistrationListener mRegistrationListener=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mNsdManager= (NsdManager) this.getSystemService(Context.NSD_SERVICE);
final ServerSocket mServerSocket;
final ArrayList<String> listName = new ArrayList<String>();
Integer localPort = 0;
final ListView list = (ListView) findViewById(R.id.listView1);
listName.add("arunima");
listName.add("abhishek");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1,listName);
list.setAdapter(adapter);
try {
mServerSocket = new ServerSocket(0);
localPort = mServerSocket.getLocalPort();
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
Log.v("service registrd", "i am on folks");
Toast.makeText(getApplicationContext(), "Registerd", Toast.LENGTH_LONG).show();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
Log.v("service registration fail", "can not register service kumar ravi");
}
};
mDiscoveryListner = new NsdManager.DiscoveryListener() {
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("cannot stop service", "service discovery failed");
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("can not start", "Can not start discovery kumar ravi "+errorCode);
}
#Override
public void onServiceLost(NsdServiceInfo service) {
// TODO Auto-generated method stub
}
#Override
public void onServiceFound(NsdServiceInfo service) {
// TODO Auto-generated method stub
Log.v("service found", "we found the service");
if(!service.getServiceType().equals("_myapp.tcp.")){
}
else if(service.getServiceName().equals("kumar")){
}
else {
listName.add(service.getServiceName());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "Finally found the service "+service.getServiceName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
// TODO Auto-generated method stub
}
#Override
public void onDiscoveryStarted(String serviceType) {
// TODO Auto-generated method stub
Log.v("Service Discovery Started", "Searching of Service Discovery");
}
};
Log.v("registerd port", localPort.toString());
final NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(localPort);
serviceInfo.setServiceName("kumar");
serviceInfo.setServiceType("_myapp.tcp.");
//mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
Button startBroadcast = (Button) findViewById(R.id.button1);
Button startListen = (Button) findViewById(R.id.button2);
startBroadcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
});
startListen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.discoverServices("_myapp.tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListner);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListner);
Log.v("Stopped", "Scanning stopped"); }
catch(Exception e){
Log.v("some error in unregistring service", e.toString());
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

how to link the class shown below with main activity

here is the code of the class which i created which extends MainActivity and how can i call this from MainActivity?
I'm trying to figure out where I went wrong on referencing my surface view class, not my view. I only did the view as an example. Here is my main class:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewExample extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
ball=BitmapFactory.decodeResource(getResources(),R.drawable.tennis_ball);
x = y = 0;
setContentView(v);
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t;
SurfaceHolder holder;
boolean isItOk=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk ==true)
{
//drawing
if(holder.getSurface().isValid()) {
continue;
}
Canvas c=holder.lockCanvas();
c.drawARGB(255,150,150,10);
c.drawBitmap(ball, x+(ball.getWidth()/4), y+(ball.getHeight()), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause()
{
isItOk=false;
while(true) {
try {
t.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
break;
}
}
public void resume()
{
isItOk=true;
t=new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
The much i got is that you want to go SurfaceViewExample from your main activity for that you need to use intent on button click like
Intent i = new Intent(this, SurfaceViewExample.class);
startActivity(i) ;
and you have to add a permission in menifest to got to that activity like
<activity android:enabled="true" android:name="SurfaceViewExample" />
and you can see these links also
Calling one Activity from another in Android
http://developer.android.com/reference/android/content/Intent.html

Categories