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.
Related
So I have made a simple heating text control app and it all works with permissions and all of that but it uses 2 fragments and inside them are two textboxes which I want to have the same text in -- phone number. I cannot get the edittext in rel2 to be changed by rel1.
Rel 1:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;
import static android.content.SharedPreferences.*;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel1 extends Fragment{
Button BtnHOFF, BtnHON, BtnHST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel1, container, false);
final View view2 = inflater.inflate(R.layout.rel2, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnHOFF = (Button) view.findViewById(R.id.Hoff);
BtnHON = (Button) view.findViewById(R.id.Hon);
BtnHST = (Button) view.findViewById(R.id.Hstatus);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
saveB = (Button) view.findViewById(R.id.saveB);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnHOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=ON", txtPhoneNo.getText().toString());
}
});
BtnHON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=OFF", txtPhoneNo.getText().toString());
Log.i(getActivity().toString(), "Done!");
}
});
BtnHST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
Log.i("me", "Saved!");
Toast.makeText(getActivity().getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG).show();
((EditText) view2.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 2:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel2 extends Fragment {
Button BtnWOFF, BtnWON, BtnWST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel2, container, false);
final View view1 = inflater.inflate(R.layout.rel1, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnWOFF = (Button) view.findViewById(R.id.Woff);
BtnWON = (Button) view.findViewById(R.id.Won);
BtnWST = (Button) view.findViewById(R.id.Wstatus);
saveB = (Button) view.findViewById(R.id.saveB);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnWOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=ON", txtPhoneNo.getText().toString());
}
});
BtnWON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=OFF", txtPhoneNo.getText().toString());
}
});
BtnWST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
((EditText) view1.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
Log.d("me", "Saved!");
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 1 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Hon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Heating ON (REL1 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hoff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hon"
android:layout_marginTop="13dp"
android:text="Heating OFF (REL1 ON)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hoff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:text="07599070551"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
Rel 2 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Won"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Water ON (REL2 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Woff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Won"
android:layout_marginTop="13dp"
android:text="Water OFF (Rel2 On)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Wstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Woff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
EDIT:
I would like the edit text in Rel2 to change when I press save in rel1 therefore the phone number boxes will always be the same.
rel1
EDIT 2:
I have fixed the shared prefs issue but I would still like to know if anyone can make the textboxes the same wherether that is on text update or on save button press.
There are two ways you can do this.
Using Interface
Create an interface with a method something like TextChangeListener and declare a method onTextChange(String text).
interface TextChangeListener{
void onTextChange(String number);
}
Implement the interface in the HostActivity
class HostActivity extends Activity implements TextChangeListener{
...
void onTextChange(String number){
secondFragment.updateNumber(number)
}
...
}
In FirstFragment call the activity using the implmented interface in the afterTextChanged() listener of TextWatcher
class FirstFragment extends Fragment{
private TextChangeListener activity;
#Override
public onAttach(Context context){
if(context instanceof TextChangeListener){
activity = (TextChangeListener) context;
}
}
phNumEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
activity.onTextChange(s.toString);
}
...
);
...
}
In SecondFragment on receiving the call from activity, update the EditText with new data.
class SecondFragment extends Fragment{
...
public void updateNumber(String number){
editText.setText(number);
}
}
Using EventBus
Use EventBus to post an event from FirstFragment. The event will contain the data to be populated in SecondFragment. The SecondFragment will Subscribe to the event and on receiving the event the data will be populate into the EditText.
The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?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"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.
I have a MainActivity with a ListView and an add Button. When the user clicks the add Button it takes you to another activity the CreateActivity for you to enter in data or strings into the editText boxes. After that you click the create Button and it adds the strings to the ListView it shows up, but every time I try to add another item to the ListView it just overrides the first item and doesn't add on to the ListView.
MainActivity.java with listView and add button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
Button addButton;
ListView itemListView;
public static ArrayList<String> arrayList;
public static ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle editTextData = getIntent().getExtras();
if(editTextData != null){
itemListView = (ListView)findViewById(R.id.itemListView);
String data = editTextData.getString("data");
arrayList = new ArrayList<String>();
arrayList.add(data);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
if(data != ""){
arrayAdapter.notifyDataSetChanged();
}
}
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivity(intent);
}
});
}
}
activity_main xml with listView and add button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.MainActivity"
android:weightSum="1">
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/addButton" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/itemListView"
/>
</RelativeLayout>
CreateActivity.java with four editText boxes and create button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.brian.inventoryapp.R.id.editTextItem;
public class CreateActivity extends AppCompatActivity {
EditText editTextItem;
EditText editTextModel;
EditText editTextSerial;
EditText editTextID;
Button createButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getIntent();
editTextItem = (EditText)findViewById(R.id.editTextItem);
editTextModel = (EditText)findViewById(R.id.editTextModel);
editTextSerial = (EditText)findViewById(R.id.editTextSerial);
editTextID = (EditText)findViewById(R.id.editTextID);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("data", item);
startActivity(intent);
}
});
}
}
activity_create xml with the four editText boxes and the create button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:id="#+id/activity_create"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.CreateActivity">
<TextView
android:text="Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextItem" />
<TextView
android:text="Model Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:id="#+id/textView2"
android:layout_below="#+id/editTextItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextModel" />
<TextView
android:text="Serial Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextModel"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextSerial" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_below="#+id/editTextID"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="#+id/imageButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<TextView
android:text="ID Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
every time you restart the MainActivity, it is be created, the onCreate method was executed .one method you can use the comment method:use startactivityforResult;
you can read this question how to manage startactivityforResult.the second method is to set MainActivity model to SingleInstance.
You are starting MainActivity over and over again, clearing all data previously loaded.
Try this solution
Main activity:
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
public static final int CREATE_REQUEST = 1;
private Button addButton;
private ListView itemListView;
private ArrayList<String> arrayList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemListView = (ListView) findViewById(R.id.itemListView);
addButton = (Button) findViewById(R.id.addButton);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivityForResult(intent, CREATE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CREATE_REQUEST) {
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("data");
arrayList.add(item);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
}
}
}
}
In your CreateActivity change createButton listener to this one:
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("data", item);
setResult(RESULT_OK, intent);
finish();
}
});
Yes it will assume as if the MainActivity is started for the first time so you should use startActivityForResult() method instead of startActivity().This will continue your MainActivity and do not override your list View.
My problem is when I click bSA button I encounter error and the activity closes.
java.lang.runtimeexception unable to start activity componentinfo ...
here is my code
Data.java :
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Data extends Activity implements View.OnClickListener {
Button start, startFor;
EditText sendET;
TextView gotAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
initialize();
}
private void initialize() {
start = (Button) findViewById(R.id.bSA);
startFor = (Button) findViewById(R.id.bSAFR);
sendET = (EditText) findViewById(R.id.etSend);
gotAnswer = (TextView) findViewById(R.id.tvGot);
start.setOnClickListener(this);
startFor.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bSA:
String bread = sendET.getText().toString();
Bundle basket = new Bundle();
basket.putString("key", bread);
Intent a = new Intent(getApplicationContext(), OpenedClass.class);
a.putExtras(a);
startActivity(a);
break;
case R.id.bSAFR:
break;
}
}
}
get.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etSend" android:layout_gravity="center_horizontal"/>
<Button
android:layout_below="#+id/etSend"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Activity"
android:id="#+id/bSA"/>
<Button
android:layout_toLeftOf="#+id/bSA"
android:layout_alignTop="#+id/bSA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Activity for Results"
android:id="#+id/bSAFR"/>
<TextView
android:layout_below="#+id/bSAFR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:id="#+id/tvGot"/>
</RelativeLayout>
=============================================================
OpenedClass.java
package com.example.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
public class OpenedClass extends Activity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
TextView question, test;
Button returnData;
RadioGroup selectionList;
String gotBread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
initialize();
Bundle gotBasket = getIntent().getExtras();
gotBread = gotBasket.getString("key");
question.setText(gotBread);
}
private void initialize() {
question = (TextView) findViewById(R.id.tvQuestion);
test = (TextView) findViewById(R.id.tvText);
returnData = (Button) findViewById(R.id.bReturn);
returnData.setOnClickListener(this);
selectionList = (RadioGroup) findViewById(R.id.rgAnswers);
selectionList.setOnCheckedChangeListener(this);
}
#Override
public void onClick(View view) {
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
switch (arg1) {
case R.id.rCrazy:
break;
case R.id.rFun:
break;
case R.id.rBoth:
break;
}
}
}
send.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Hosein is ..."
android:id="#+id/tvQuestion"/>
<RadioGroup
android:id="#+id/rgAnswers"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Crazy"
android:id="#+id/rCrazy"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Super Fun"
android:id="#+id/rFun"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Both"
android:id="#+id/rBoth"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Return"
android:id="#+id/bReturn"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/tvText"/>
</LinearLayout>
Intent a = new Intent(getApplicationContext(), OpenedClass.class);
a.putExtras(a);
You cannot put a inside itself. This causes infinite recursion and stack overflow.
You probably wanted
a.putExtras(basket);
I am new to android development, was following a tutorial in order to get a better understanding about fragments, but after completing the tutorial when it comes to testing I encountered this particular problem after removing a few syntax errors. In the logcat I get "threadid=1: thread exiting with uncaught exception (group=0x40a7193" I've spent almost an entire working day on it, I've looked but it seems like the solution to this problem is dependent upon the source code, I've been on a number of links but everywhere there's some source code provided and I haven't found a solution for my problem so far, any help will be much appreciated. Here is My Code:
MainActivity.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements ToolbarFragments.ToolbarListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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 onButtonClick(int fontsize, String text) {
TextFragment textFragment =
(TextFragment) getSupportFragmentManager().findFragmentById(R.id.text_fragment);
textFragment.changeTextProperties(fontsize, text);
}
}
Here is TextFragment.java:
package com.example.fragmentsexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private static TextView textview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.text_fragment, container,false);
textview=(TextView) view.findViewById(R.id.textView1);
return view;
}
public void changeTextProperties(int fontsize, String text){
textview.setTextSize(fontsize);
textview.setText(text);
}
}
Here is ToolbarFragments.java
package com.example.fragmentsexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolbarFragments extends Fragment {
private static int seekvalue=10;
private static EditText editText;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
activityCallback=(ToolbarListener) activity;
}
catch (Exception e){
throw new ClassCastException(activity.toString()+ "must implement ToolbarListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle SavedInstanceState){
View view=inflater.inflate(R.layout.toolbar_fragment, container, false);
editText=(EditText) view.findViewById(R.id.editText1);
final SeekBar seekbar=(SeekBar) view.findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this);
final Button button=(Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked(View v){
activityCallback.onButtonClick(seekvalue,editText.getText().toString());
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
seekvalue=progress;
}
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
Here is the activity_main.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=".MainActivity" >
<fragment
android:id="#+id/toolbar_fragment"
android:name="com.example.fragmentexample.ToolbarFragments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/toolbar_fragment" />
<fragment
android:id="#+id/text_fragment"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
Here is the text_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/fragtwo"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Here is the toolbar_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="#string/button"/>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1"
android:layout_marginTop="14dp" />
</RelativeLayout>
Any help any sort of help will be appreciated it is my second post here i apologize for a messy post