[Help]Create App - Java for Android App Development

Hi Guys,
I open this thread because I need help:I would like to create an app which do a login on a website(my website)...any suggest?I'm a noob D:... ty

Try going through this tutorial
http://www.edumobile.org/android/android-development/login-request-example-in-android/

Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?

ultimatexemnas said:
Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?
Click to expand...
Click to collapse
I use this two methods to log on the internet. As you understand downloadUrl(URL); gives you what site tells you. I can recommend you to use special URLs in order to log in(for example example.com/auth.php?req=login&pass=....&login=....)
Code:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}

Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<

ultimatexemnas said:
Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<
Click to expand...
Click to collapse
URL of your site with sonething containig your password and login and server should give you answer if your pass and login are in database or not

So,in the end it should be something like this?
package com.example.LoginRequestExample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel; 
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((private String downloadUrl(String mywebsite.ukcom) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL mywebsite.ukcom);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
}
);
}}
Right?Are there any errors?

I've clean it up for you.
Replace google.com with your website.
Make sure your website takes username and password as a GET input.
The variable responseContent takes the result of the website after login in.
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel;
String username, password, responseContent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName = (EditText) this.findViewById(R.id.txtUname);
txtPassword = (EditText) this.findViewById(R.id.txtPwd);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
if (txtPassword.getText().toString().trim().length() < 1
|| txtUserName.getText().toString().trim().length() < 1) {
Toast.makeText(LoginRequestExample.this,
"Please enter your login details",
Toast.LENGTH_SHORT).show();
} else {
username = txtUserName.getText().toString().trim();
password = txtPassword.getText().toString().trim();
downloadUrl("http://google.com/login.php?u=" + username + "&password=" + password);
}
}
});
}
private void downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
// int response = conn.getResponseCode();
// Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
responseContent = contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

Related

Face Detection in Background Service

I am making an android app which requires to capture image using front camera using android service. Also we need to detect face in the image so obtained. But when calling the detectfaces() function, the app unfortuantely stops. I am posting the code for it here. Please help me find out where i am going wrong.
here is my code..!!!!
package com.android.camerarecorder;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {
static final int MAX_FACES = 5;
//private static final String TAG = "Recorder";
public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera;
public static boolean mPreviewRunning;
public static TextView jpgName;
public static ImageView jpgView;
public static ImageView imageView;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.jpgview);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
jpgName = (TextView)findViewById(R.id.jpgname);
jpgView = (ImageView)findViewById(R.id.jpgview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(CameraRecorder.this,RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
//finish();
}
});
Button btnStop = (Button) findViewById(R.id.StopService);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(CameraRecorder.this, RecorderService.class));
}
});
}
@override
public void surfaceCreated(SurfaceHolder holder) {
}
@override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
The above code was the activity where the service is called. The service is as follows:
package com.android.camerarecorder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.iutputStream;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecorderService extends Service
{
private SurfaceHolder sHolder;
private TextView mjpgname;
private ImageView mjpgview;
private ImageView mimageview;
Bitmap bm;
Bundle bundle = new Bundle();
String filename;
private int cameraId = 0;
//a variable to control the camera
private Camera mCamera;
final static String DEBUG_TAG = "Test";
Uri imageFileUri;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
@override
public void onCreate()
{
super.onCreate();
sHolder=CameraRecorder.mSurfaceHolder;
mCamera = CameraRecorder.mCamera;
mjpgname= CameraRecorder.jpgName;
mjpgview = CameraRecorder.jpgView;
mimageview=CameraRecorder.imageView;
}
@SuppressWarnings("deprecation")
 @override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
} else {
mCamera = Camera.open(cameraId);
}
}
//mCamera = Camera.open();
SurfaceView sv = new SurfaceView(getApplicationContext());
sv=CameraRecorder.mSurfaceView ;
try {
mCamera.setPreviewDisplay(sHolder);
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
// TODO Auto-generated method stub
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
// FileOutputStream outStream = null;
try{
imageFileUri = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS = getContentResolver().openOutputStream(
imageFileUri);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
filename = getRealPathFromURI(imageFileUri);
File imgFile = new File(filename);
if(imgFile.exists())
{
bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mjpgview.setImageBitmap(bm);
}
detectFaces();
// mjpgname.setText("success");
/*
Intent i = new Intent(RecorderService.this, FaceDetect.class);
//Add your data to bundle
bundle.putString("Filepath", filename) ;
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);*/
/* final File images = Environment.getExternalStorageDirectory();
String filePath = "magic";
String final_path = images+"/"+filePath;
outStream = new FileOutputStream(final_path);
outStream.write(data);
outStream.close();*/
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
private void detectFaces() {
if(null != bm){
int width = bm.getWidth();
int height = bm.getHeight();
FaceDetector detector = new FaceDetector(width, height,CameraRecorder.MAX_FACES);
Face[] faces = new Face[CameraRecorder.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
//canvas.setBitmap(cameraBitmap);
canvas.drawBitmap(bm, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
// int facesFound = detector.findFaces(cameraBitmap, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y - eyeDistance ,
(int)midPoint.x + eyeDistance,
(int)midPoint.y + eyeDistance, drawPaint);
}
}
// Camera_timer.key = eyeDistance;
// tv.setText(eyeDistance+"");
String filepath = Environment.getExternalStorageDirectory()
+ "/facedetect" +System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
// cameraBitmap.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mimageview.setImageBitmap(bitmap565);
// imageView.setImageBitmap(cameraBitmap);
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader((Context) mCall,contentUri, proj, null, null,null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
// TODO Auto-generated method stub
}
@override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Updating tabs to new tab fragments

Hi all,
I had an app that was working about 3 years ago that I decided to update for the latest android sdk.I was using tabs but have decided to update to tab fragments with swipe.The problem I'm having is how to lay out the code.I have updated my app but have a few errors.Specifically the Book Now tab usually has a book now form so people can fill it out and upon clicking submit it sms's it to me.Below is the code for BookNowFragmnet.java.
I should mention that the tab and swipe part works flawlessly.I dont have a logcat because it wont build without removing the code
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String phoneNo = edittextPhone.getText().toString();
String message = editTextProblem.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem areas are as follows;
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
dfwcomputer said:
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
Click to expand...
Click to collapse
So you are asking for the method "getBaseContext" within an onClickListener... it does not have a method called that... like it's telling you it's undefined
It would probably be a better idea to use application context either by direct use of getApplicationContext or by a "final" reference maybe...
dfwcomputer said:
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
Click to expand...
Click to collapse
BookNowFragment is not extended from the base type of Context that is expected in the arguments.
dfwcomputer said:
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
Click to expand...
Click to collapse
dfwcomputer said:
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
Click to expand...
Click to collapse
Actually the last to are just repeats of the previous really... I'm guessing here but it seems you may have skipped ahead of where you should be in a learning sense.. cause it seems to be like your running without being knowing how to jog kinda thing. Not attempting to be condescending, just I'm a trainer and always attempt to point this stuff out when I see it
Maybe go back and do some of the basics again, and include fragments etc
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
dfwcomputer said:
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
Click to expand...
Click to collapse
hmmm, well if thats all thats wrong with it, all I could offer is for you to send me the packaged src+res and I will have a look... if it takes less than 20 min to fix and get running I have no problem fixing it for you. If it doesn't and maybe takes longer then I may have to leave it. Should be quick though, up to you
But with the info I gave you should be able to fix those 4 issues...if not hit me up on hangouts and will talk you though it
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
dfwcomputer said:
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
Click to expand...
Click to collapse
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
deanwray said:
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
Click to expand...
Click to collapse
lol now I have less faith ill be fixing it..... Ill let you know thanks again
sent you a private message m8, because there is some personal info in the app
dfwcomputer said:
sent you a private message m8, because there is some personal info in the app
Click to expand...
Click to collapse
fixed and sent private msg with class
Thanks again, I apreciate it.I have changed the personal info and posted the working code here incase someone else has a similar issue.
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
//edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
//editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String strPhoneNo = "0000000000";
TextView txtName = (TextView) rootView.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView.findViewById(R.id.edittextPhone);
TextView txtProblem = (TextView) rootView.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n"
+ strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I forgot the date and time picker arrrrrrrgh
I've added the following 2 classes which have no errors and seem to function fine.
DatePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
TextView txtDate;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
txtDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
}
TimePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtTime.setText(hourOfDay+":"+minute);
}
}
I then updated BookNowFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
Button btnChangeDate,btnChangeTime;
TextView txtDisplayDate,txtDisplayTime;
DatePicker datePicker;
TimePicker timePicker;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow,
container, false);
showCurrentDateOnView();
showCurrentTimeOnView();
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
// edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
// editTextProblem = (EditText)
// rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strPhoneNo = "00000000";
TextView txtName = (TextView) rootView
.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView
.findViewById(R.id.edittextPhone);
//TextView txtDate = (TextView) rootView.findViewById(R.id.date);
TextView txtProblem = (TextView) rootView
.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
//String strDate = "Date: " + txtDate.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n" + strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
new Intent(SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
// display current date
public void showCurrentDateOnView() {
txtDisplayDate = (TextView) findViewById(R.id.txtDate);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
txtDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
datePicker.init(year, month, day, null);
}
// display current time
public void showCurrentTimeOnView() {
txtDisplayTime = (TextView) findViewById(R.id.txtTime);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
txtDisplayTime.setText(
new StringBuilder().append(hour)
.append(":").append(minute));
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment(txtDisplayDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The problem areas are all under BookNowFragment.java;
1. Under "showCurrentDateOnView" the both findViewById says undefined for the type.I have tried adding rootView but didnt work.
2. Under "showCurrentTimeOnView" both findViewById says undefined for the type.I have tried adding rootView but didnt work.
3. under "showDatePickerDialog" and "showTimePickerDialog" both the getSupportFragmentManager methods show the error "The method getSupportFragmentManager() is undefined for the type BookNowFragment"
4. I also have errors with "onCreateOptionsMenu".I worked out some of them by adding getActivity (see new code below) but it still shows the error "The method onCreateOptionsMenu(Menu) of type BookNowFragment must override or implement a supertype method"
PHP:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Think there simple issues although I'm simple as well so I could be understating it.

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

[Q] How to pass image from one intent to another

Hi friends,
Here is my code for displaying details and images from MySQL database,All i want to do is pass the detail with image to other inner page through intent.Please help me im new in android.
Activity 1
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi") public class News_events extends Fragment {
private String jsonResult;
private String url = "<URL PHP FILES>";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("<URL IMAGE FOLDER>"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("<URL IMAGE FOLDER>"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("google");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Activity 2
Code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}

Image positioning in Listview search

I have a problem with the pictures when I use the search then the app always takes the first picture instead of the picture that belongs.
I added two pictures where you can see what I mean by "Adrenaline".
Can someone help me by chance?
I would be very happy.
Sorry for my bad English.
Code:
package com.0000.00000;
import androidx.appcompat.app.AppCompatActivity;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import android.webkit.*;
import android.animation.*;
import android.view.animation.*;
import java.util.*;
import java.text.*;
import java.util.HashMap;
import java.util.ArrayList;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdRequest;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.AdListener;
import android.content.Intent;
import android.net.Uri;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class PerksActivity extends Activity {
private ArrayList<Integer> image_list = new ArrayList<>();
private HashMap<String, Object> map_var = new HashMap<>();
private String saved = "";
private double length = 0;
private double r = 0;
private String value1 = "";
private String value2 = "";
private String value3 = "";
private String value4 = "";
private ArrayList<HashMap<String, Object>> map_list = new ArrayList<>();
private LinearLayout linear1;
private LinearLayout linear2;
private LinearLayout linear3;
private LinearLayout linear10;
private LinearLayout linear11;
private LinearLayout linear12;
private TextView textview4;
private AdView adview1;
private LinearLayout linear15;
private LinearLayout linear16;
private LinearLayout linear44;
private ListView listview1;
private EditText edittext1;
private LinearLayout linear929;
private TextView textview8;
private InterstitialAd admob;
private AdListener _admob_ad_listener;
private Intent page_intent = new Intent();
private AlertDialog.Builder popup;
@Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.perks);
initialize(_savedInstanceState);
initializeLogic();
}
private void initialize(Bundle _savedInstanceState) {
linear1 = (LinearLayout) findViewById(R.id.linear1);
linear2 = (LinearLayout) findViewById(R.id.linear2);
linear3 = (LinearLayout) findViewById(R.id.linear3);
linear10 = (LinearLayout) findViewById(R.id.linear10);
linear11 = (LinearLayout) findViewById(R.id.linear11);
linear12 = (LinearLayout) findViewById(R.id.linear12);
textview4 = (TextView) findViewById(R.id.textview4);
adview1 = (AdView) findViewById(R.id.adview1);
linear15 = (LinearLayout) findViewById(R.id.linear15);
linear16 = (LinearLayout) findViewById(R.id.linear16);
linear44 = (LinearLayout) findViewById(R.id.linear44);
listview1 = (ListView) findViewById(R.id.listview1);
edittext1 = (EditText) findViewById(R.id.edittext1);
linear929 = (LinearLayout) findViewById(R.id.linear929);
textview8 = (TextView) findViewById(R.id.textview8);
popup = new AlertDialog.Builder(this);
listview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> _param1, View _param2, int _param3, long _param4) {
final int _position = _param3;
if (_position == 0) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 1) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 2) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
}
});
edittext1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
final String _charSeq = _param1.toString();
map_list = new Gson().fromJson(saved, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
length = map_list.size();
r = length - 1;
for(int _repeat17 = 0; _repeat17 < (int)(length); _repeat17++) {
value1 = map_list.get((int)r).get("a").toString();
value2 = map_list.get((int)r).get("b").toString();
value3 = map_list.get((int)r).get("c").toString();
if (!(_charSeq.length() > value1.length()) && value1.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value2.length()) && value2.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value3.length()) && value3.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
map_list.remove((int)(r));
}
}
}
r--;
}
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
}
@Override
public void afterTextChanged(Editable _param1) {
}
});
_admob_ad_listener = new AdListener() {
@Override
public void onAdLoaded() {
admob.show();
}
@Override
public void onAdFailedToLoad(int _param1) {
final int _errorCode = _param1;
SketchwareUtil.showMessage(getApplicationContext(), "Werbung konnte nicht Geladen werden!!!".concat(String.valueOf((long)(_errorCode))));
}
@Override
public void onAdOpened() {
}
@Override
public void onAdClosed() {
}
};
}
private void initializeLogic() {
adview1.loadAd(new AdRequest.Builder().addTestDevice("0815")
.build());
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perksstriche));
map_var.put("b", getResources().getString(R.string.perksueberlebende));
map_var.put("c", getResources().getString(R.string.perksstriche02));
map_var.put("d", getResources().getString(R.string.perksinfopopupheadername));
map_var.put("e", getResources().getString(R.string.perksinfopopuptxtname));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkablenkungname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenadamfrancisname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel30name));
map_var.put("d", getResources().getString(R.string.perkablenkungpopupheadername));
map_var.put("e", getResources().getString(R.string.perkablenkungpopuptxt));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkadrenalinname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenmegthomasname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel40name));
map_var.put("d", getResources().getString(R.string.perkadrenalinpopupheadername));
map_var.put("e", getResources().getString(R.string.perkadrenalinpopuptxt));
map_list.add(map_var);
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
saved = new Gson().toJson(map_list);
image_list.add(R.drawable.perk_ueberlebende);
image_list.add(R.drawable.adam_francis_perk_ablenkung);
image_list.add(R.drawable.meg_thomas_perk_adrenalin);
}
@Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
default:
break;
}
}
public class Listview1Adapter extends BaseAdapter {
ArrayList<HashMap<String, Object>> _data;
public Listview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
_data = _arr;
}
@Override
public int getCount() {
return _data.size();
}
@Override
public HashMap<String, Object> getItem(int _index) {
return _data.get(_index);
}
@Override
public long getItemId(int _index) {
return _index;
}
@Override
public View getView(final int _position, View _view, ViewGroup _viewGroup) {
LayoutInflater _inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View _v = _view;
if (_v == null) {
_v = _inflater.inflate(R.layout.perkssearch, null);
}
final LinearLayout linear1 = (LinearLayout) _v.findViewById(R.id.linear1);
final ImageView imageview1 = (ImageView) _v.findViewById(R.id.imageview1);
final LinearLayout linear2 = (LinearLayout) _v.findViewById(R.id.linear2);
final LinearLayout linear3 = (LinearLayout) _v.findViewById(R.id.linear3);
final TextView textview1 = (TextView) _v.findViewById(R.id.textview1);
final TextView textview2 = (TextView) _v.findViewById(R.id.textview2);
final TextView textview3 = (TextView) _v.findViewById(R.id.textview3);
textview1.setText(map_list.get((int)_position).get("a").toString());
textview2.setText(map_list.get((int)_position).get("b").toString());
textview3.setText(map_list.get((int)_position).get("c").toString());
imageview1.setImageResource(image_list.get((int)_position));
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebende)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksvonkeinezuordnungname)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebendendwightfairfieldname)) ) {
textview2.setTextColor(0xFF8BC34A);
}
return _v;
}
}
@Deprecated
public void showMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
@Deprecated
public int getLocationX(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[0];
}
@Deprecated
public int getLocationY(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[1];
}
@Deprecated
public int getRandom(int _min, int _max) {
Random random = new Random();
return random.nextInt(_max - _min + 1) + _min;
}
@Deprecated
public ArrayList<Double> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Double> _result = new ArrayList<Double>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add((double)_arr.keyAt(_iIdx));
}
return _result;
}
@Deprecated
public float getDip(int _input){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, _input, getResources().getDisplayMetrics());
}
@Deprecated
public int getDisplayWidthPixels(){
return getResources().getDisplayMetrics().widthPixels;
}
@Deprecated
public int getDisplayHeightPixels(){
return getResources().getDisplayMetrics().heightPixels;
}
}

Categories

Resources