I need to take the date information from a CalendarView into another activity so that i can store the information in a database properly.
The activity I need to use the date on is this:
package com.example.calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import static com.example.calendar.Constants.DATE;
import static com.example.calendar.Constants.CONTENT_URI;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CreateAppointment extends Activity implements OnClickListener{
private static String[] FROM = { _ID, DATE, TIME, TITLE, DETAILS};
private static String ORDER_BY = TIME + " ASC";
AppointmentsData appointments;
CalendarView calendar;
String string;
EditText nameTextBox;
EditText timeTextBox;
EditText detailsTextBox;
Button createButton;
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
createButton = (Button) findViewById(R.id.apptSave);
nameTextBox = (EditText)findViewById(R.id.apptName);//Assign the global name box
timeTextBox = (EditText)findViewById(R.id.apptTime);//Assign the global time box
detailsTextBox = (EditText)findViewById(R.id.apptDetails);//Assign the global details box
calendar = (CalendarView)findViewById(R.id.calendar);
createButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
string = "row";
}
private void addAppointment(String string) {
/* Insert a new record into the Events data
source. You would do something similar
for delete and update. */
String getTitle = nameTextBox.getText().toString();
String getTime = timeTextBox.getText().toString();
String getDetails = detailsTextBox.getText().toString();
db = appointments.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DATE, calendar.getDate());
values.put(TIME, getTime);
values.put(TITLE, getTitle);
values.put(DETAILS, getDetails);
getContentResolver().insert(CONTENT_URI, values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.apptSave:
addAppointment(string);
finish();
break;
}
}
}
And I need to extract the date from the MainActivity, which is:
package com.example.calendar;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import static android.provider.BaseColumns._ID;
import static com.example.calendar.Constants.TABLE_NAME;
import static com.example.calendar.Constants.TIME;
import static com.example.calendar.Constants.TITLE;
import static com.example.calendar.Constants.DETAILS;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity implements OnClickListener {
private AppointmentsData appointments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View createButton = findViewById(R.id.btn_create);
View editButton = findViewById(R.id.btn_viewEdit);
View deleteButton = findViewById(R.id.btn_delete);
View moveButton = findViewById(R.id.btn_move);
View searchButton = findViewById(R.id.btn_search);
View translateButton = findViewById(R.id.btn_translate);
View exitButton = findViewById(R.id.exit);
createButton.setOnClickListener(this);
editButton.setOnClickListener(this);
deleteButton.setOnClickListener(this);
moveButton.setOnClickListener(this);
searchButton.setOnClickListener(this);
translateButton.setOnClickListener(this);
exitButton.setOnClickListener(this);
appointments = new AppointmentsData(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.btn_create:
i = new Intent(this, CreateAppointment.class);
startActivity(i);
break;
case R.id.btn_viewEdit:
i = new Intent(this, EditViewAppointment.class);
startActivity(i);
break;
case R.id.btn_move:
i = new Intent(this, MoveAppointment.class);
startActivity(i);
break;
case R.id.btn_delete:
i = new Intent(this, DeleteAppointment.class);
startActivity(i);
break;
case R.id.btn_search:
i = new Intent(this, SearchAppointment.class);
startActivity(i);
break;
case R.id.btn_translate:
i = new Intent(this, TranslateAppointment.class);
startActivity(i);
break;
case R.id.exit:
finish();
break;
}
}
}
EDIT:
Also, here is my layout for the main activity:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="225dp"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin" >
<CalendarView
android:id="#+id/calendar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="2dip"
android:layout_marginTop="2dip"
android:stretchColumns="*" >
<TableRow>
<Button
android:id="#+id/btn_create"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/create" />
<Button
android:id="#+id/btn_viewEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/viewEdit" />
</TableRow>
<TableRow>
<Button
android:id="#+id/btn_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/delete" />
<Button
android:id="#+id/btn_move"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/move" />
</TableRow>
<TableRow>
<Button
android:id="#+id/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/search" />
<Button
android:id="#+id/btn_translate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/translate" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/exit"/>
</LinearLayout>
How can I solve this?
to transfer data between activities you can use use baskets
The activity which you generate the data
i = new Intent(this, DeleteAppointment.class);
i.putExtra("name", strFirstName);
startActivity(i);
The activity which you are retrieving the data
#Override
protected void onHandleIntent(Intent intent)
{
String action = intent.getAction();
String name= intent.getStringExtra("name");
}
Related
so i have a project where im implementing a google sign in, i followed this tutorial on how to do that, but when i did, all my XML files appear blank. i made changes to the original MainActivity.java and the activity_main.xml file. i woudl think that only the activity_main.xml would be affected, but all of my XML files appear blank. when i try to run the app, i get
"Error:Content is not allowed in prolog.
" and
"Execution failed for task '.app:builderInfoDebugLoader'"
this is my activity main where i implement the google sign in:
package com.example.mayankthakur.personalprojecttrial2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.signin.SignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private LinearLayout prof_section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Picture;
private Button continueBut;
private static final int REQ_CODE = 9001;
String name;
Intent nameSave;
private GoogleApiClient mGoogleApiClient;
public static final String prefsName = "com.example.mayankthakur.personalprojecttrial2";
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
prof_section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.logoutBtn);
SignIn = (SignInButton) findViewById(R.id.gSignIn);
Name = (TextView) findViewById(R.id.nameSpace);
Email = (TextView) findViewById(R.id.emailSpace);
Prof_Picture = (ImageView) findViewById(R.id.profilePicture);
continueBut = (Button) findViewById(R.id.button2);
continueBut.setOnClickListener(this);
SignOut.setOnClickListener(this);
SignIn.setOnClickListener(this) ;
prof_section.setVisibility(View.GONE);
continueBut.setVisibility(View.GONE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onClick (View v) {
switch (v.getId()) {
case R.id.gSignIn:
signIn();
break;
case R.id.logoutBtn:
signOut();
break;
/*// This is the shared preference
SharedPreferences.Editor prefs = getSharedPreferences(prefsName, MODE_PRIVATE).edit();
//adding a value to the preference
prefs.putString("name", name);
prefs.apply();
nameSave = new Intent(MainActivity.this, Activity2.class);
MainActivity.this.startActivity(nameSave);
*/
}
}
#Override
public void onConnectionFailed (#NonNull ConnectionResult connectionResult){
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQ_CODE );
}
private void signOut(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleReuslt(GoogleSignInResult result){
if(result.isSuccess())
{
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String imgUrl = acct.getPhotoUrl().toString();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Name.setText(personName);
Email.setText(personEmail);
Glide.with(this).load(imgUrl).into(Prof_Picture);
updateUI(true);
}
else
{
updateUI(false);
}
}
private void updateUI(boolean isLogin){
if(isLogin)
{
prof_section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
}
else
{
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleReuslt(result);
}
}
}
this is my XML file where i added the buttons and stuff for the google sign in:\
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/activity_main"
android:orientation="vertical"
tools:context="com.example.mayankthakur.personalprojecttrial2.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/prof_section"
android:layout_marginLeft="20dp"
android:layout_marginTop = "50dp"
android:weightSum="1">
<ImageView
android:id="#+id/profilePicture"
android:layout_width="90dp"
android:layout_height="100dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:src="#drawable/photo"
android:layout_weight="0.25" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/nameSpace"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name Display"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/emailSpace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Email Display"
android:textSize="14dp"
android:textStyle="bold" />
<Button
android:id="#+id/logoutBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/gSignIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp">
</com.google.android.gms.common.SignInButton>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please Sign in in order to make use of all of the features of the app"
android:textAlignment="center"
android:textSize="20dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Continue"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"/>
</LinearLayout>
any help would be greatly appreciated, and if any of you require any more code please do ask
thanks in advance!
I want to add a button to one of my activities (that displays a news article), so when the user clicks the button the article is opened in their browser. So far I have added the button in my xml and it appears. I'm just having some trouble with the click listener. Below is my code, i'm getting an error for 'setOnClickListener' which is 'Non-static method 'setOnClickListener(android.view.View.onClickListener)' cannot be referenced from a static content.
I'm not sure what this means! maybe i'm not calling the method in the right place or there is just an error with the method itself?
Please could someone take a look, thanks!
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONException;
import org.json.JSONObject;
public class NewsItemActivity extends AppCompatActivity {
//Declare java object for the UI elements
private TextView itemTitle;
private TextView itemDate;
private TextView itemContent;
private NetworkImageView itemImage;
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_item);
itemTitle = (TextView) findViewById(R.id.itemTitle);
itemDate = (TextView) findViewById(R.id.itemDate);
itemContent = (TextView) findViewById(R.id.itemContent);
itemImage = (NetworkImageView) findViewById(R.id.itemImage);
EDANewsApp app = EDANewsApp.getInstance();
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String url = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id="+itemId;
JsonObjectRequest request = new JsonObjectRequest(url, listener, errorListener);
app.requestQueue.add(request);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
};
activity_news_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NewsItemActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/itemTitle"
android:layout_margin="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#3183b9"/>
<TextView
android:id="#+id/itemDate"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:textSize="16sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/itemContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="16sp"
/>
<Button
android:id="#+id/BrowserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View in browser"
android:layout_marginLeft="15dp"
style="#style/BrowserButton"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Change
Button.setOnClickListener(new View.OnClickListener() { ... });
to
Button button = (Button) findViewById(R.id.BrowserButton);
button.setOnClickListener(new View.OnClickListener() { ... });
You need to call the setOnClickListener method on an instance of Button, not on the class itself.
The problem is this :
Button.setOnClickListener(new View.OnClickListener() {
You have to declare it out of onCreate() as you did with your Textviews as :
Button btn;
Why?
Because if you put it on onCreate() you wont be able to use this object out of onCreate() so it's recomendable to put it as a public object.
Then in your onCreate() do this :
btn = (Button)findViewById(R.id.BrowserButton);
Then you do the OnclickListener() as follows :
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
I'm still getting an error for onClickListener, saying it 'cannot resolve symbol'.
Make sure that you've imported this :
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
You can do it doing this :
Add implements OnClickListener { as follows :
public class NewsItemActivity extends AppCompatActivity implements View.OnClickListener {
Then on your Button you do this :
btn = (Button)findViewById(R.id.BrowserButton);
btn.setOnClickListener(this);
Then add a switch case as follows :
public void onClick(View v) {
switch(v.getId()) {
case R.id.BrowserButton:
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
break;
}
}
It crashes on this line: alListView.setAdapter(adapter); It worked all last night and I didn't make any changes... I made a few formatting changes, maybe I deleted something I shouldn't have.
package com.grumpy.multipages;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainPage extends AppCompatActivity {
AlDatabaseAdapter AlHelper;
private ListView alListView;
//AlHelper helper;
private static final String TAG = "MultiPages";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
AlHelper = new AlDatabaseAdapter(this);
//SQLiteDatabase db = AlHelper.getWritableDatabase();
String myHouses = LoadDB();
String[] values = myHouses.split("\n");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
//alListView.setAdapter(adapter);
alListView.setAdapter(adapter); // CRASHES HERE
Log.d(TAG, "Main Page ");
//Button myBtn = (Button)findViewById(R.id.button1_Button);
Button myBtn1 = (Button)findViewById(R.id.button1_Button);
myBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddHouse.class);
//intent.putExtra("refer", "Called from Main Page");
startActivity(intent);
}
});
}
private String LoadDB() {
// Need to get list of Houses from Database
Log.d(TAG, "Calling LoadDB ");
String myHouses = AlHelper.getData();
Log.d(TAG, "Returning From LoadDB ");
Log.d(TAG,myHouses);
return myHouses;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
// Layout page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainPage">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAddHouse"
android:id="#+id/button1_Button" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal"
android:choiceMode="singleChoice"
android:clickable="true"
tools:listitem="#android:layout/simple_list_item_1" />
Before:
alListView.setAdapter(adapter); // CRASHES HERE
you should assign to alListView your widget, and from your code it looks like its null at above line.
So add:
alListView = (ListView)findViewById(R.id.listView);
This may be null pointer exception because you declared your Listview(i.e. alListView) but you missed to define it i.e alListView=(ListView)findviewById...
code and trying to set adapter in a null object reference where it crashed.
I have a sample barcode scanner app using this library.
onActivityResult does not update the textView nor editText.
I did some search around and noticed that this is a common problem.
onActivityResult i get my value that i pass through, i can log and toast the value but does not work on setText() method.
Edit: I'm using fragments.
Fragment A is where the button, edit & textview are, Fragment B is the barcode scanner and i use popBackStack() to return to fragment A(received data from Fragment B);
Here is my code:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public static final int DIALOG_FRAGMENT = 1;
public TextView textView;
public TextView textView2;
public TextView textView3;
public TextView textView4;
public EditText editText;
public Button button;
public String barcode;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
textView = (TextView)rootView.findViewById(R.id.textView);
textView2 = (TextView)rootView.findViewById(R.id.textView2);
textView3 = (TextView)rootView.findViewById(R.id.textView3);
textView4 = (TextView)rootView.findViewById(R.id.textView4);
editText = (EditText)rootView.findViewById(R.id.editText);
button = (Button)rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
// setText();
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_FRAGMENT && resultCode == Activity.RESULT_OK) {
// System.out.println("ok");
barcode = data.getExtras().getString("barcode");
// edit_barcode.setText(value);
setText();
Toast.makeText(getActivity(), barcode, Toast.LENGTH_SHORT).show();
// System.out.println(barcode);
// edit_barcode.setText(barcode);
}
}
public void setText() {
System.out.println(barcode);
textView.setText(barcode);
textView2.setText(barcode);
textView3.setText(barcode);
textView4.setText(barcode);
editText.setText(barcode);
}
public void scanBarcode(){
Barcode barcode = new Barcode();
barcode.setTargetFragment(PlaceholderFragment.this, DIALOG_FRAGMENT);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, barcode);
fragmentTransaction.addToBackStack("VIEW");
fragmentTransaction.commit();
}
}
Barcode Class:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
public class Barcode extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mScannerView = new ZBarScannerView(getActivity());
return mScannerView;
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void handleResult(Result rawResult) {
if(!rawResult.getContents().isEmpty()){
mScannerView.startCamera();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("barcode", rawResult.getContents());
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
getFragmentManager().popBackStack();
}else {
// Toast.makeText(getActivity(),"Fail",Toast.LENGTH_SHORT).show();
getFragmentManager().popBackStack();
mScannerView.startCamera();
}
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
}
my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/button">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView4"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="Barcode"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Try these
1 ) Instead of
barcode = data.getExtras
try
barcode = data.getStringExtra("barcode")
2) Instead of initiating barcode
String barcode;
Try doing this in your onActivityResult,
String barcode = data.getExtras().getString("barcode");
3 ) Instead of putting data directly into intent, use a bundle.
Bundle b = new Bundle();
b.putString ("barcode", rawResult.getContent());
Intent i = new intent();
i.putExtras (b);
In your onActivityResult
Bundle b = getIntent.getExtras();
String s = b.getString("barcode");
Then use s where you need it.
EDIT: the complete code now
package com.example.shopkart;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
public class netbanking extends Activity {
datamanager dm;
String name,mailid;
String[] productnamearray;
int[] amount_product,id_array;
boolean[] checkarray;
int tablesize,finalbill;
Spinner spinner_banks;
WebView wv1;
Button btnbankselect;
// #Override
// public void onBackPressed() {
//
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.netbanking);
dm=new datamanager(this);
wv1=(WebView) findViewById(R.id.wv1);
btnbankselect=(Button) findViewById(R.id.btnbankselect);
spinner_banks=(Spinner) findViewById(R.id.spinner_banks);
productnamearray=getIntent().getExtras().getStringArray("productnamearray");
checkarray=getIntent().getExtras().getBooleanArray("checkarray");
id_array=getIntent().getExtras().getIntArray("id_array");
name=getIntent().getExtras().getString("name");
mailid=getIntent().getExtras().getString("mailid");
finalbill=getIntent().getExtras().getInt("finalbill");
setspinnervalues();
btnbankselect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos=spinner_banks.getSelectedItemPosition();
switch (pos) {
case 0:
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl("http://www.canarabank.in");
// Intent i1=new Intent(Intent.ACTION_VIEW);
// i1.setData(Uri.parse("http://www.google.com"));
// startActivity(i1);
break;
case 1:
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl("http://www.federalbank.co.in");
// Intent i2=new Intent(Intent.ACTION_VIEW);
// i2.setData(Uri.parse("http://www.facebook.com"));
// startActivity(i2);
break;
case 2:
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl("http://www.icicibank.com");
// Intent i3=new Intent(Intent.ACTION_VIEW);
// i3.setData(Uri.parse("http://www.icicibank.com"));
// startActivity(i3);
break;
case 3:
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl("http://www.hdfcbank.com");
// Intent i4=new Intent(Intent.ACTION_VIEW);
// i4.setData(Uri.parse("http://www.hdfcbank.com"));
// startActivity(i4);
break;
case 4:
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl("http://www.onlinesbi.com");
// Intent i5=new Intent(Intent.ACTION_VIEW);
// i5.setData(Uri.parse("http://www.onlinesbi.com"));
// startActivity(i5);
break;
}
}
});
}
public void setspinnervalues()
{
String[] arrvalues={"Canara Bank","Federal Bank","HDFC bank","ICICI bank","State bank of India"};
ArrayAdapter<String> arrap=new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_spinner_item,arrvalues);
spinner_banks.setAdapter(arrap);
}
}
the xml page:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#F7F7F7"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Net banking Page"
android:textColor="#4B0082"
android:textSize="65px"
android:textStyle="bold"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose your bank from the below list"
android:textColor="#4B0082"
android:textSize="40px"
android:textStyle="bold"
android:layout_gravity="center"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner_banks"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginTop="20px"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="25px"
android:text="Go to bank"
android:id="#+id/btnbankselect"
android:background="#4B0082"
android:textColor="#FFFFFF"
android:textSize="40px"
/>
<WebView
android:layout_width="wrap_content"
android:layout_height="110px"
android:id="#+id/wv1"
/>
</LinearLayout
The browser force closes and the webview doesnt open.help!!
I have removed the spinner event, and the webview loads on a button click, instead of a spinner itemselected event.
Try code below for browser intent :
//replace your bank link here
String link="http://www.bank.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
startActivity(intent);