Cannot save entity from android app to Google App Engine backend - java

I am following the examples given in the Google tutorial to create a Google App Engine backend for my android app.
In the tutorial, the MainActivity is as follows:
import java.io.IOException;
import java.util.Date;
import android.os.AsyncTask;
import android.content.Context;
import com.cloudnotes.noteendpoint.Noteendpoint;
import com.cloudnotes.noteendpoint.model.Note;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new EndpointsTask().execute(getApplicationContext());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
Note note = new Note().setDescription("Note Description");
String noteID = new Date().toString();
note.setId(noteID);
note.setEmailAddress("E-Mail Address");
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
}
This worsk fine and the entities are created everytime i run the app.So i modified it by adding textfields to get the values of description and email from the user and got this as the new MainActivity
public class MainActivity extends Activity implements View.OnClickListener{
EditText descriptionTF;
EditText emailTF;
Button submitBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button) findViewById(R.id.submitButton);
descriptionTF = (EditText) findViewById(R.id.descriptionTextField);
emailTF = (EditText) findViewById(R.id.emailTextField);
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
String descrptn = descriptionTF.getText().toString();
String email = emailTF.getText().toString();
String noteID = new Date().toString();
try {
Note note = new Note();
note.setDescription(descrptn);
note.setId(noteID);
note.setEmailAddress(email);
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
#Override
public void onClick(View v) {
if (v.getId()== R.id.submitButton) {
new EndpointsTask().execute(getApplicationContext());
}
}
}
Now nothing happens when i click the submit button.
I am guessing the problem is from me calling new EndpointsTask().execute(getApplicationContext()); from the onClick() method instead of the onCreate() method as it was done in the tutorial.Does anyone know a way around this?

Finally solved this problem by moving the onClick() method to the onCreate() method like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button) findViewById(R.id.submitButton);
descriptionTF = (EditText) findViewById(R.id.descriptionTextField);
emailTF = (EditText) findViewById(R.id.emailTextField);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId()== R.id.submitButton) {
new EndpointsTask().execute(getApplicationContext());
}
}
});
}

Related

How to get text from url and put it inside textView?

I'm new in android development and I really can't figure out how to do that. So, I'm building an android app that stream music online via url. There is an url that shows current song. here is the url
I created a textView in my activity_main file to put current song text inside it, but I can't figure out how. I understand that I need to make variable url, then I need to parse that URL and put it inside text view. Or not?
Here is my MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView currentSong;
private boolean playPause;
private MediaPlayer mediaPlayer;
private boolean initialStage = true;
private ProgressBar pgsBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.audioStreamBtn);
currentSong = (TextView) findViewById(R.id.currentSong);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
pgsBar = findViewById(R.id.progressBar);
pgsBar.setVisibility(View.GONE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
btn.setText("Stop");
if (initialStage) {
new Player().execute("stream url ...");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
} else {
btn.setText("Play");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
playPause = false;
}
}
});
}
class Player extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
initialStage = true;
playPause = false;
btn.setText("Play");
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (Exception e) {
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (pgsBar.getVisibility() == View.VISIBLE) {
pgsBar.setVisibility(View.GONE);
btn.setEnabled(true);
}
mediaPlayer.start();
initialStage = true;
}
#Override
protected void onPreExecute() {
mediaPlayer.reset();
super.onPreExecute();
pgsBar.setVisibility(View.VISIBLE);
btn.setEnabled(false);
}
}
}
How do I pull out this text and put it in my textView "currentSong"?
You can use okHttp library to make a network request to URL and it will get back the response as string. Modify the response according to your liking and use that value for setText() of text view .
Use Retrofit or Volley to make a URL request.
possible duplicate of Make an HTTP request with android

Android ZXING barcodescan put result value in string

I am trying to get the result value in a string after there has been scanned.
but it wont work.
I already figured out how to put it in a toast(maketext) that works but a string I cant figure it out.
here's the code please help me.
cpackage com.example.stage.absa;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import java.io.IOException;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.net.Uri;
import java.net.URL;
public class MainActivity extends AbsRuntimePermission {
String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZxingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
remove the String declaration and instead move it as a class member
public void handleResult(Result result) {
//String resultCode = result.getText();
resultCode = result.getText();
like:
myClass extends Activity... {
String resultCode;
}
now you can assign the result code in the hadnleResult callback and use it in the same activity whenever you need it!
Edit:
you have an inner class, i would get rid of that and directly implement the ZXingScannerView.ResultHandler interface:
example:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
//scannerView.setResultHandler(new ZxingScannerResultHandler());
scannerView.setResultHandler(this);
setContentView(scannerView);
scannerView.startCamera();
}
//class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
//}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}
I will go with this or something similar, depending on how you are handling the scanner view
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private String resultCode;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
resultCode = rawResult.getText();
//now use resultCode
}
}

How to get the Data from DialogFragment to MainActivity in Android?

I create a application using DialogFragment.I want to get the Data from DialogFragment and setText in the MainActivity. In my Code I successfully Created the AlertDialog.But I con't able to get the EditText value to MainActivity.Application is crashed.Please help me to solve the problem.Any Help would be I really Appreciate.
MainActivity.java :
public class MainActivity extends ActionBarActivity {
Button showDialog;
TextView showText;
String myNameStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.myBtn);
showText = (TextView)findViewById(R.id.showText);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
showText.setText(myNameStr);
}
}
MyAlert.java:
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
MainActivity mainActivity = new MainActivity();
mainActivity.setMyNameStr(value);
dialog.dismiss();
}
}
Using this Procedure Application is Crashed.
replace from
MainActivity mainActivity = new MainActivity();
to:
Activity mainActivity = (MainActivity)getActivity();
Create an interface like-
CustomDialogInterface.java
public interface CustomDialogInterface {
// This is just a regular method so it can return something or
// take arguments if you like.
public void okButtonClicked(String value);
}
and modify your MyAlert.java by-
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
CustomDialogInterface customDI;
public MyAlert(CustomDialogInterface customDI)
{
this.customDI = customDI;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
dialog.dismiss();
customDI.okButtonClicked(value);
}
void setCustomDialogInterface(CustomDialogInterface customDialogInterface){
this. customDI = customDialogInterface;
c}
}
And implement CustomDialogInterface in your MainActivity and overide method okButtonClicked()
When onClick will be called then your MainActivity's onButtonClicked will be called .
and change showAlert to -
class MainActivity..... implements CustomDialogInterface {
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.show(getFragmentManager(), "My New Alert");
}
#Overide
public void okButtonClicked(String value){
// handle
}
}
or use following code :
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.setCustomDialogInterface(new CustomDialogInterface() {
#Override
public void okButtonClicked(String value) {
//handle click
}
});
myAlert.show(getFragmentManager(), "My New Alert");
}
you can achieve this using a interface,by sending your data from a fragment to main activity,below i have edited your complete code and its working fine....
Here is the code with example
Your Main Activity
package com.example.dialogfragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity implements SetName{
Button showDialog;
TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.button1);
showText = (TextView)findViewById(R.id.textView2);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
}
#Override
public void setMyName(String string) {
// TODO Auto-generated method stub
showText.setText(string);
}
}
Your Alert
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
SetName setname;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
setname = (SetName) a;
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
// MainActivity mainActivity = new MainActivity();
setname .setMyName(value);
//setname = (SetName)
// setname = (SetName)getActivity();
dialog.dismiss();
}
}
Create a Interface
public interface SetName {
void setMyName(String string);
}
Now what you should do is create onAttach in your alertFragment and call your interface..
public void renameFile(){
RenameFileDialog dialog = new RenameFileDialog();
dialog.show(getSupportFragmentManager(), DIALOG_RENAME_FILE);
}
public void syncFolders(String value) {
//some code
new UpdateFolderAsyncTask().execute();
}
update listview with new updated value after performining operation in main activity class syncFolders() in DialogFragment class
CustomDialogFragment extends DialogFragment{
//some logic for performining operation
String updatedValue=edittext.getText();
MainActivity activity=(MainActivity)getActivity();
activity.syncFolders(updatedValue);
}

click on spinner item and call asynctask of second spinner list item

I am developing an app in which i need to fill spinner from one webservice and there are second spinner are also exist which fill after select first spinner item. second(spinner B) is depend on spinner A. i got list for A but problem with b spinner.
my basic requirement is when i select the item of spinner "A" it will load all item of Spinner "b"
here is code ::
package com.CaribPay;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.Setting.CustomParser;
public class Register2 extends Activity implements OnItemClickListener {
private Button BtnReg2Next;
private EditText EdtxReg2Streetadd1,
EdtxReg2Streetadd2,
EdtxReg2City,
EdtxReg2Zipcode;
private Spinner
SpnrReg2Contry,
SpnrReg2Agent,
SpnrReg2State,
SpnrReg2PrimaryCurr,
SpnrReg2SecondaryCurr;
private CustomParser cstParsr = new CustomParser();
private String[] Regstrationstep1;
private String[] strCountry,strProvince;
private String[] Primarysecondarycur;
private int globPosition;
private String strSelecteccontry;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register2);
GetDataFromLastPage();
new FillSpinnerTask().execute();
}
private class FillSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strCountry = cstParsr.LoadCountriesForMobApp(getApplicationContext());
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strCountry != null)
{
for(int i=0;i<strCountry.length;i++)
{
Log.i("TAG","strCountry"+strCountry[i]);
}
}
FillView();
}
}
}
private void FillView() {
BtnReg2Next = (Button)findViewById(R.id.BtnReg2Next);
EdtxReg2Streetadd1 = (EditText)findViewById(R.id.EdtxReg2Streetadd1);
EdtxReg2Streetadd2= (EditText)findViewById(R.id.EdtxReg2Streetadd2);
EdtxReg2City = (EditText)findViewById(R.id.EdtxReg2City);
EdtxReg2Zipcode = (EditText)findViewById(R.id.EdtxReg2Zipcode);
SpnrReg2Contry = (Spinner)findViewById(R.id.SpnrReg2Contry);
SpnrReg2Agent = (Spinner)findViewById(R.id.SpnrReg2Agent);
SpnrReg2State = (Spinner)findViewById(R.id.SpnrReg2State);
SpnrReg2PrimaryCurr = (Spinner)findViewById(R.id.SpnrReg2PrimaryCurr);
SpnrReg2SecondaryCurr= (Spinner)findViewById(R.id.SpnrReg2SecondaryCurr);
if(strCountry != null)
{
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strCountry);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2Contry.setAdapter(languagelist);
}
SpnrReg2Contry.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3)
{
strSelecteccontry = strCountry[position];
new FillProvinceSpinnerTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
/*SpnrReg2State.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(strProvince == null)
{
new FillProvinceSpinnerTask().execute();
}
return true;
}
});*/
BtnReg2Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(EdtxReg2Streetadd1.getText().toString().equalsIgnoreCase("")|
EdtxReg2Streetadd2.getText().toString().equalsIgnoreCase("")|
EdtxReg2City.getText().toString().equalsIgnoreCase("")|
EdtxReg2Zipcode.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getApplication(),getString(R.string.nullmessage),Toast.LENGTH_LONG).show();
}else
{
Intent Registration2 = new Intent(Register2.this,Register3.class);
startActivity(Registration2);
finish();
}
}
});
}
private void GetDataFromLastPage() {
// TODO Auto-generated method stub
Intent intent = getIntent();
Regstrationstep1 = new String[9];
Regstrationstep1 = intent.getStringArrayExtra("Regstrationstep1");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int Pos, long arg3) {
// TODO Auto-generated method stub
}
private class FillProvinceSpinnerTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(
Register2.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.MsgPleasewait));
this.dialog.show();
this.dialog.setCancelable(false);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
strProvince = cstParsr.LoadProvinceFromCountryForMobApp(getApplicationContext(),strSelecteccontry);
return null;
}
#Override
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
this.dialog = null;
} catch (Exception e) {
e.printStackTrace();
}
if(strProvince != null)
{
Primarysecondarycur = strProvince[0].split("~");
strProvince[0] = "Please Select a State";
ArrayAdapter languagelist = new ArrayAdapter(
Register2.this,
android.R.layout.simple_spinner_item,
strProvince);
languagelist.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
SpnrReg2State.setAdapter(languagelist);
}
}
}
}
}
The issue with OnItemSelectedListener is that it selects first value on declaration. To avoid the first call do something like this :
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(count>0) {
// do what you want on item selection
} else {
count++;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}

Webview is blank or loading same page for different urls

A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
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.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.

Categories

Resources