Android Saved Instance State Not Saving (Dual Activity) - java

Hi my MainActivity and MainActivity2 are supposed to be saving the instance state, but when I rotate the device into landscape it does not save the time, the timer restarts. My app is a log in verication that displays time stamps when you click the verify button, right now I am trying to save the timer when I rotate the device, but it is not saving I will include the code below thanks. Update when I comment out onRestoreInstanceState and run the program it says that I am getting a NumberFormatException in onSaveInstanceState not sure.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.security_token_app, PID: 15284
java.lang.NumberFormatException: For input string: "seconds remaining: 50"
at java.lang.Long.parseLong(Long.java:594)
at java.lang.Long.parseLong(Long.java:636)
at com.example.security_token_app.MainActivity.onSaveInstanceState(MainActivity.java:117)
at android.app.Activity.performSaveInstanceState(Activity.java:1609)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1447)
at android.app.ActivityThread.callActivityOnSaveInstanceState(ActivityThread.java:5071)
at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4400)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4364)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4439)
at android.app.servertransaction.StopActivityItem.execute(StopActivityItem.java:41)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:145)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7078)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
package com.example.security_token_app;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity
{
private static String SHARED_PREF_NAME = "SharedPrefFile";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private static String TIMESTAMP_KEY = "TIMESTAMP_KEY";
private TextView countDownTextView;
TextView passCodeTextView;
static int passCode;
static String currentDateTime;
static ArrayList<String> arrayIntegerList = new ArrayList<String>();
Button verifyButton;
private static String LOG_TAG = "log state 1";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTextView = (TextView)findViewById(R.id.textView4_time_remaining);
passCodeTextView= (TextView)findViewById(R.id.textView3_passCode_int);
verifyButton = (Button)findViewById(R.id.button1);
sharedPreferences = getSharedPreferences(SHARED_PREF_NAME,MODE_PRIVATE);
createPassCode();
new CountDownTimer(60000, 1000)
{
#Override
public void onTick(long timeUntillFinished)
{
countDownTextView.setText("seconds remaining: " + timeUntillFinished / 1000 % 60);
}
#Override
public void onFinish()
{
createPassCode();
start();
}
}.start();
verifyButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String check = sharedPreferences.getString(TIMESTAMP_KEY, null);
Log.i("k1","timestamp: "+check);
if(check != null)
{
arrayIntegerList.add(check);
Toast.makeText(getBaseContext(), "restored", Toast.LENGTH_SHORT).show();
}
openSecondaryActivity();
}
});
}
public void createPassCode()
{
int minute = Calendar.getInstance().get(Calendar.MINUTE);
passCode=minute*1245 + 10000;
String timeStamp = getTimeStamp();
arrayIntegerList.add(timeStamp);
String passCodeStr = Integer.toString(passCode);
passCodeTextView.setText(passCodeStr);
}
public void openSecondaryActivity()
{
Intent intent = new Intent(this, MainActivity2.class);
intent.putExtra("timestamp_list", arrayIntegerList);
startActivity(intent);
}
public static int getPassCode()
{
return passCode;
}
public static String getTimeStamp()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateTime = dateFormat.format(new Date());
return currentDateTime;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState)
{
super.onSaveInstanceState(outState);
TextView textView = (TextView) findViewById(R.id.textView4_time_remaining);
long savedData = Long.parseLong(textView.getText().toString());
outState.putLong("outStateKey", savedData);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
long storedData = savedInstanceState.getLong("outStateKey");
TextView textView = (TextView)findViewById(R.id.textView4_time_remaining);
textView.setText(Long.toString(storedData));
}
}
package com.example.security_token_app;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity
{
SharedPreferences sharedPreferences;
private static String SHARED_PREF_NAME = "SharedPrefFile";
private static String TIMESTAMP_KEY = "TIMESTAMP_KEY";
ArrayList<String> arrayList = new ArrayList<String>();
ListView listView;
Button clearButton;
int count;
String item;
static ArrayAdapter<String> adapter;
static boolean isSaved = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = (ListView) findViewById(R.id.listView1);
clearButton = (Button) findViewById(R.id.passButton);
sharedPreferences = getSharedPreferences(SHARED_PREF_NAME,MODE_PRIVATE);
ArrayList<String> timestampList = (ArrayList<String>)getIntent().getSerializableExtra("timestamp_list");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, timestampList);
listView.setAdapter(adapter);
clearButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
count = adapter.getCount();
String checkFirstPass = sharedPreferences.getString(TIMESTAMP_KEY,null);
Log.i("k2","timestamp: "+checkFirstPass);
if(checkFirstPass==null)
{
item = adapter.getItem(count - 1);
}
else if(checkFirstPass!=null)
{
item = adapter.getItem(count-2);
}
adapter.clear();
adapter.add(item);
saveTimeStamp(item);
}
});
}
public void saveTimeStamp(String lastItem)
{
if(!lastItem.isEmpty())
{
sharedPreferences = getSharedPreferences(SHARED_PREF_NAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TIMESTAMP_KEY, lastItem);
editor.apply();
Toast.makeText(getBaseContext(), "time stamp saved", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "nothing saved", Toast.LENGTH_SHORT).show();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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/root_constraint_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linear_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout="#layout/activity_main">
<TextView
android:id="#+id/textView1_blueBox"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="0.25"
android:background="#color/sky_blue"
android:text="test" />
<TextView
android:id="#+id/textView2_passCode_string"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:textAlignment="center"
android:text="PASS CODE"
android:textStyle="bold"
android:textSize="38sp"/>
<TextView
android:id="#+id/textView3_passCode_int"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:textAlignment="center"
android:textSize="38sp"
android:textStyle="bold"
android:text="test" />
<TextView
android:id="#+id/textView4_time_remaining"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:textAlignment="center"
android:textSize="24sp"
tools:text="1:00 seconds remaining"/>
<Button
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="Verify"
android:textStyle="bold"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity2">
<LinearLayout
android:id="#+id/linear_layout1"
android:layout_width ="match_parent"
android:layout_height ="match_parent"
android:orientation="vertical"
tools:layout="#layout/activity_main">
<TextView
android:id="#+id/textView1_blueBox"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="0.25"
android:background="#color/sky_blue" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textStyle="bold"
android:dividerHeight="32dp"
/>
<Button
android:id="#+id/passButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:text="PASS"
android:textStyle="bold"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

ViewModel
Use ViewModelenter link description here
It's no problem to rotate
You can learn about the login module of Android studio
enter image description here

Use ViewModel to solve this problem
if you need a practical implementation of how to use this here

Related

Cannot see widgets in tab layout in android studio

I am facing the problem of cannot see widgets in tab layouts. I have created textview and button in Overview Fragment but I cannot see them when run code. Is it right to initialize textviews and buttons in oncreateview() of fragment which we don't want to transfer to another tab. I have searched a lot about my problem but cannot get any hint. Code is given below:
package com.example.progluattempt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
public class GlucosePlotterTips extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glucose_plotter_tips);
TabLayout Tablayout1 = findViewById(R.id.Tablayout1);
TabItem OverviewTab = findViewById(R.id.Overviewtab);
TabItem HistoryTab = findViewById(R.id.Historytab);
TabItem TipsTab = findViewById(R.id.Tipstab);
ViewPager Viewpager1 = findViewById(R.id.viewpagery1);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Tablayout1.getTabCount());
Viewpager1.setAdapter(pagerAdapter);
Tablayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Viewpager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
//PgeAdapter
package com.example.progluattempt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
private int numoftabs;
public PagerAdapter(FragmentManager fm, int numoftabs){
super(fm);
this.numoftabs = numoftabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new OverviewFragment();
case 1:
return new HistoryFragment();
case 2:
return new TipsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numoftabs;
}
}
//Main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".GlucosePlotterTips">
<com.google.android.material.tabs.TabLayout
android:id="#+id/Tablayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004">
<com.google.android.material.tabs.TabItem
android:id="#+id/Overviewtab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overview" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Historytab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="History" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Tipstab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tips" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpagery1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
//fragmentOverview
<FrameLayout 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"
tools:context=".OverviewFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="183dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewov2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:text="#string/overview1"
android:textColor="#color/black"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewov3"
android:layout_width="match_parent"
android:layout_height="46dp"
android:text="TextView"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="#+id/buttonov2"
android:layout_width="277dp"
android:layout_height="93dp"
android:layout_gravity="center"
android:text="#string/planner"
android:textColor="#color/black"
android:textSize="24sp"
app:backgroundTint="#color/Yellow" />
//OverviewFragment
package com.example.progluattempt;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
TextView Results, Condition;
Button Mybuttonov2;
public OverviewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Results = (TextView) view.findViewById(R.id.textViewov2);
Intent i =getActivity().getIntent();
String LatestReading=i.getStringExtra("TimeofReading");
Results.setText("Last Checked: " +LatestReading);
//type
Condition = (TextView) view.findViewById(R.id.textViewov3);
String TypeofDiab = i.getStringExtra("Concentration");
Condition.setText("" +TypeofDiab);
//Button
Mybuttonov2 = (Button) view.findViewById(R.id.buttonov2);
//to display conditon of user
if(Condition.getText() != null){
String num;
int numi=0;
num = Condition.getText().toString();
try{
numi = Integer.parseInt(num);
}catch(NumberFormatException ex){
}
if(numi <= 70){
System.out.println("Hypoglycemia");}
else if(numi >=70 & numi <= 140){
System.out.println("Fine");}
else if(numi>140 & numi <200){
System.out.println("Prediabetes");}
else {
System.out.println("Hyperglycemia");
}
}
//to add click event for button
Mybuttonov2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i3 = new Intent(getActivity(), SensorScreen.class );
startActivity(i3);
}
});
return view;
}
}
Logcat
When run emulator

Android: Calculate price from clicked items in listview. App crashes in total activity Logcat:Invalid float: ""

Im a noob in this so please bear with me. I have a listview of food and drinks with price then a proceed button which will show the order summary and total amount in other activity. After I click some items then click the proceed button, the app crash "Unfortunately appname has stopped." But when I click proceed button without clicking any items it displays the layout of the order summary. Therefore the error occurs in the passing of data. In logcat I noticed first Invalid float: "" I have no idea how to fix this.
I used SQLite for database of items
This is the code of activity for order summary and total amount where the error seems to appear.
package edu.sti.snapchit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.StringTokenizer;
import java.lang.String;
public class TotalsActivity extends AppCompatActivity{
MyApp mApp;
EditText et_summary;
TextView tv_total;
Button btn_code;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totals);
btn_code = (Button) findViewById(R.id.btn_code);
mApp=((MyApp)getApplicationContext());
et_summary = (EditText) findViewById(R.id.et_summary);
tv_total = (TextView) findViewById(R.id.tv_total);
et_summary.setText(mApp.getGlobalVarValue());
String str = mApp.getGlobalVarValue();
StringTokenizer st = new StringTokenizer(str,"Php");
String test="";
float total=0;
int count =0;
while(st.hasMoreElements())
{
test = st.nextElement().toString().substring(0,1);
if(count>0)
total += Float.parseFloat(test);
count++;
}
tv_total.setText("Total:" + total+"");
mApp.setGlobalClear();
btn_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(TotalsActivity.this, GeneratorActivity.class);
startActivity(intent);
}
});
}
public boolean isFloat(String input)
{
try
{
Float.parseFloat(input);
return true;
}
catch(Exception e)
{
return false;
}
}
}
Total 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:background="#android:color/holo_orange_light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Order Summary "
android:textSize="30dp"
android:id="#+id/textV"
android:layout_gravity="center_horizontal"
android:layout_weight="0.07"
android:background="#android:color/holo_blue_dark"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/background_light"
android:layout_marginTop="6dp">
<EditText
android:id="#+id/et_summary"
android:layout_width="match_parent"
android:layout_height="267dp"
android:layout_gravity="center_horizontal"
android:layout_weight="0.55"
android:inputType="text"
android:textSize="24dp"
android:hint="Summary"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total : "
android:textSize="30dp"
android:layout_weight="0.07"
android:id="#+id/tv_total"/>
</LinearLayout>
<Button
android:id="#+id/btn_code"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:background="#drawable/buttonborder"
android:clickable="true"
android:text="Proceed to Qr Code Generator"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
Code for Food Activity which contains the listview
package edu.sti.snapchit;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.HashMap;
public class NewFoodsActivity extends AppCompatActivity {
MyApp mApp;
private HashMap<String, Location> locations;
ListView listView1;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db=openOrCreateDatabase("Foods_DB", Context.MODE_PRIVATE, null);
setContentView(R.layout.new_foods);
locations = loadLocationData();
addListenerButton();
initializeUI();
}
public void initializeUI()
{
String[] foodies = getFoodNames();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, foodies);
listView1.setAdapter(adapter);
}
private String[] getFoodNames()
{
String[] foodies = new String[locations.size()];
foodies = locations.keySet().toArray(foodies);
return foodies;
}
private void displaySelectedFoodInfo(String foodName)
{
}
public void showMessage(String title,String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
private HashMap<String, Location>loadLocationData()
{
HashMap<String, Location>locations = new HashMap<String, Location>();
Cursor c=db.rawQuery("SELECT * FROM table_foods order by food_id
asc",null);
StringBuffer buffer = new StringBuffer();
while(c.moveToNext())
{
locations.put("- "+c.getString(1).toString()+" [Php
"+c.getString(2).toString()+"]", new Location(Integer.parseInt(c.getString(0)),c.getString(1).toString(),Double.parseDouble(c.getString(2))));
}
return locations;
}
public void addListenerButton()
{
final Context context = this;
Button btnAdd = (Button)findViewById(R.id.btn_add);
Button btnProceed = (Button)findViewById(R.id.btnProceed);
Button btn_drinks = (Button)findViewById(R.id.btn_drinks);
Button btn_foods = (Button)findViewById(R.id.btn_foods);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> Arg0, View view, int
position, long id) {
Object o = listView1.getItemAtPosition(position);
String pen = o.toString();
mApp=((MyApp)getApplicationContext());
mApp.setGlobalVarValue(pen);
Toast.makeText(getApplicationContext(), "Item Added" +
""+ pen, Toast.LENGTH_LONG).show();
}
}
);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewAddFoods.class);
startActivity(intent);
}
});
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, TotalsActivity.class);
startActivity(intent);
}
});
btn_foods.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewFoodsActivity.class);
startActivity(intent);
}
});
btn_drinks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, NewDrinksActivity.class);
startActivity(intent);
}
});
}
}
Food 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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center_horizontal"
android:orientation="vertical"
android:background="#android:color/holo_orange_light">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Food Items"
android:textAlignment="center"
android:textSize="30sp"
android:background="#android:color/holo_blue_dark"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<Button
android:id="#+id/btn_foods"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:text="Foods"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<Button
android:id="#+id/btn_drinks"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:text="Drinks"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="350dp"
android:id="#+id/listView1"
android:background="#android:color/background_light"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp"
>
<Button
android:id="#+id/btn_add"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Add Snacks"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
<Button
android:id="#+id/btnProceed"
android:layout_width="192dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Proceed"
android:background="#drawable/buttonborder"
android:textColor="#android:color/background_light"
android:textStyle="bold"/>
</LinearLayout>
MyApp
package edu.sti.snapchit;
import android.app.Application;
public class MyApp extends Application{
private String mGlobalVarValue="";
public String getGlobalVarValue(){
return mGlobalVarValue;
}
public void setGlobalVarValue(String str){
mGlobalVarValue += str+"\n";
}
public void setGlobalClear(){
mGlobalVarValue="";
}
}
Location
package edu.sti.snapchit;
public class Location {
private int id;
private String name;
private double price;
public Location(int id,String name, double price){
this.id = id;
this.name = name;
this.price = price;
}
#Override
public String toString(){
return this.id + " " +this.name +" " +this.price;
}
}
This is the colored red text in LOGCAT
02-20 04:37:23.624 1447-1447/edu.sti.snapchit E/AndroidRuntime: FATAL
EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
ComponentInfo{edu.sti.snapchit/edu.sti.snapchit.TotalsActivity}:
java.lang.NumberFormatException: Invalid float: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:289)
at java.lang.Float.parseFloat(Float.java:300)
at edu.sti.snapchit.TotalsActivity.onCreate(TotalsActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-20 04:37:29.372 1494-1494/edu.sti.snapchit E/dalvikvm: Could not
find class 'android.graphics.drawable.RippleDrawable', referenced from
method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-20 04:37:30.592 1494-1494/edu.sti.snapchit E/OpenGLRenderer:
Getting MAX_TEXTURE_SIZE from GradienCache 02-20 04:37:30.616
1494-1494/edu.sti.snapchit E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE
from Caches::initConstraints()
Ps. Yes I did followed a youtube tutorial in making this app. The app in vid is working perfectly while mine crashes. Either I missed something but I checked the code like 10 times or either there are parts of the vid been skipped. The uploader havent respond for days :(
I almost forgot there might also another reason that caused this. In TotalsActivity the method isFloat is never used.
enter image description here
If you've read error log carefully then it would be easy. Anyways. just replace below code
package edu.sti.snapchit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.StringTokenizer;
import java.lang.String;
public class TotalsActivity extends AppCompatActivity{
MyApp mApp;
EditText et_summary;
TextView tv_total;
Button btn_code;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totals);
btn_code = (Button) findViewById(R.id.btn_code);
mApp=((MyApp)getApplicationContext());
et_summary = (EditText) findViewById(R.id.et_summary);
tv_total = (TextView) findViewById(R.id.tv_total);
et_summary.setText(mApp.getGlobalVarValue());
String str = mApp.getGlobalVarValue();
StringTokenizer st = new StringTokenizer(str,"Php");
String test="";
float total=0;
int count =0;
while(st.hasMoreElements())
{
test = st.nextElement().toString().substring(0,1);
if(count>0 && test !=null && !test.isEmpty()){
total += Float.parseFloat(test);
}
count++;
}
tv_total.setText("Total:" + total+"");
mApp.setGlobalClear();
btn_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(TotalsActivity.this, GeneratorActivity.class);
startActivity(intent);
}
});
}
public boolean isFloat(String input)
{
if(input.isEmpty() || input == null)
return false;
try
{
Float.parseFloat(input);
return true;
}
catch(Exception e)
{
return false;
}
}
}

When clicked on select item in ListView nothing happen but no error in LogCat

I have problem select item on my ListView . When I clicked nothing happen and I could not go to the next activity because the current listView not clickable.
I tried debugging code line by line but it seems like it not enter the public void onItemClick part. Why it became like that?
Here is my code,
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewAllBills extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private Button mydebtsBtn;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_bills);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
myDebt();
}
//for new bill
public void myDebt() {
mydebtsBtn = (Button) findViewById(R.id.buttonMyDebt);
mydebtsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent page1 = new Intent(ViewAllBills.this,myDebt.class);
startActivity(page1);
}
});}
private void showBills(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String desc = jo.getString(Config.TAG_DESCRIPTION);
String amo = jo.getString(Config.TAG_AMOUNT);
HashMap<String,String> bills = new HashMap<>();
bills.put(Config.TAG_ID,id);
bills.put(Config.TAG_DESCRIPTION,desc);
bills.put(Config.TAG_AMOUNT,amo);
list.add(bills);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllBills.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_DESCRIPTION,Config.TAG_AMOUNT},
new int[]{R.id.id, R.id.description,R.id.amountBill});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllBills.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBills();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ViewAllBills.this, ViewBills.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String billId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.BILL_ID,billId);
startActivity(intent);
}
}
This is my xml file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
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:background="#color/skyBlue">
<Button android:id="#+id/buttonMyDebt"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="10dip"
android:background="#color/colorAccent"
android:textColor="#color/black"
android:textStyle="bold"
android:focusable="false"
android:text="My Debt"
android:onClick="myDebt"/>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:columnCount="3"
android:rowCount="3"
android:background="#color/softGrey"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/ids"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_gravity="center"
android:text="ID"
/>
<TextView
android:id="#+id/descriptions"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:text="Bill Description"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/amounts"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:text="Amount (RM)"
android:layout_gravity="right"
/>
</GridLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:id="#+id/listView" />
</LinearLayout>
</ScrollView>
This is my List_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:background="#color/skyBlue"
>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="3"
android:rowCount="3"
android:background="#drawable/border_style"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/id"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
/>
<TextView
android:id="#+id/amountBill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="right"
/>
</GridLayout>
</ScrollView>
Try this:
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewAllBills extends AppCompatActivity implements ListView.OnItemClickListener {
private Button mydebtsBtn;
private String JSON_STRING;
private ListView listView;
ArrayList<HashMap<String,String>> list;
ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_bills);
listView = (ListView) findViewById(R.id.listView);
list = new ArrayList<HashMap<String, String>>();
getJSON();
myDebt();
}
//for new bill
public void myDebt() {
mydebtsBtn = (Button) findViewById(R.id.buttonMyDebt);
mydebtsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent page1 = new Intent(ViewAllBills.this,myDebt.class);
startActivity(page1);
}
});}
private void showBills(){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String desc = jo.getString(Config.TAG_DESCRIPTION);
String amo = jo.getString(Config.TAG_AMOUNT);
HashMap<String,String> bills = new HashMap<>();
bills.put(Config.TAG_ID,id);
bills.put(Config.TAG_DESCRIPTION,desc);
bills.put(Config.TAG_AMOUNT,amo);
list.add(bills);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new SimpleAdapter(
ViewAllBills.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_DESCRIPTION,Config.TAG_AMOUNT},
new int[]{R.id.id, R.id.description,R.id.amountBill});
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllBills.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBills();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ViewAllBills.this, ViewBills.class);
HashMap<String,String> map = list.get(position);
String billId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.BILL_ID,billId);
startActivity(intent);
}
}
If you have an active view/focusable view in your list view then it will disable your onItemClickListener.you can try to make it unfocusable by adding: android:focusable="false" ,android:focusableInTouchMode="false"to any view that is usually focusable.
I was facing the same problem and setting android:focusableInTouchMode="false" solve my problem
My problem solved..
Actually i duplicating the scrolview layout in my list_item.xml.. after i removed the scrolview and left the gridlayout only, the select list item working..

Adding MySQL to my Java Program

My program is a barcode scanner that takes a value(string) and searches the database for the description of the project.
I cannot connect to the database, I am unable to copy the value that I get in activity_main.xml in the text field in activity_second.xml(where the database search should happen).
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
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">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nDescriere:\t" +address+ "\nImagine:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}
// #Override
//protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_second);
// }
//}
MainActivity.java
package br.exemplozxingintegration;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final int REQUEST_CODE = 0;
private TextView txResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txResult = (TextView) findViewById(R.id.txResult);
}
public void sendSecond(View view) {
Intent StartNewActivity = new Intent(this,SecondActivity.class);
startActivity(StartNewActivity);
}
public void callZXing(View view){
Intent it = new Intent(MainActivity.this, com.google.zxing.client.android.CaptureActivity.class);
startActivityForResult(it, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
txResult.setText("REZULTAT: "+data.getStringExtra("SCAN_RESULT")+" ");
}
}
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.txResult);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("textViewText", textView.getText().toString());
startActivity(intent);
}
});
}}
}
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 10.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/Android/College/getData.php?id=";
public static final String KEY_NAME = "title";
public static final String KEY_ADDRESS = "desc";
public static final String KEY_VC = "image";
public static final String JSON_ARRAY = "result";
}

Display Listview in Fragment

I am working on an Android app with Tab navigation. I have three tabs and I would like to display separate informations on each tab. On the first tab, I would like to display a list of items that are retrieved from an SQlite database. The items are entered through dialogs, which is working well. I keep the logic for the collection and display of data in the Main Activity:
package com.example.TodoList;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.app.AlertDialog;
import android.widget.SimpleCursorAdapter;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.TodoList.db.TaskContract;
import com.example.TodoList.db.TaskDBHelper;
import com.example.TodoList.fragments.ThreeFragment;
import com.example.TodoList.fragments.TwoFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListAdapter listAdapter;
private TaskDBHelper helper;
private Button btnIconTextTabs;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
//ListView listView = (ListView) findViewById(R.id.list);
//listView.setAdapter(listAdapter);
updateUI();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnIconTextTabs = (Button) findViewById(R.id.btnIconTextTabs);
//btnIconTextTabs.setOnClickListener(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputField = new EditText(this);
builder.setNegativeButton("Cancel", null);
switch (item.getItemId()) {
case R.id.action_add_task:
builder.setTitle("Add an article to your shopping list");
builder.setMessage("What would you like to add?");
builder.setView(inputField);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
builder.create().show();
return true;
case R.id.action_remove_task:
builder.setTitle("Remove an article from the shopping list");
builder.setMessage("Did you found this article?");
builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
updateUI();
}
});
case R.id.action_show_mylocation:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
//Intent intent=new Intent(this,LbsGeocodingActivity.class);
//startActivity(intent);
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(GeoLocationIntent);
}
builder.create().show();
return true;
}
private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
}
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
public void onSubmitPriceClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, SubmitPriceActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onWebViewButtonClick(View view) {
Intent intent = new
Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.batprice.com:1337"));
startActivity(intent);
finish();
}
public void onGeoLocationButtonClick(View view) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
MainActivity.this.startActivity(GeoLocationIntent);
}
/*#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnIconTextTabs:
startActivity(new Intent(MainActivity.this, IconTextTabsActivity.class));
break;
}
}*/
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
This is my First fragment, where I want to display the list items:
package com.example.TodoList.fragments;
import android.content.Context;
import android.database.SQLException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.TodoList.R;
import java.util.ArrayList;
public class OneFragment extends FragmentActivity {
public OneFragment() {
// Required empty public constructor
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(OneFragment.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
return inflater.inflate(R.layout.fragment_one, container, false);
}
/*
public static class OneFragment extends Fragment {
ListView list;
list = (ListView) view.findViewById(R.id.listview);
DataDB data = new DataDB();
ArrayAdapter<String> listAdapter;
public ListDoctorFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.listdoctor, container, false);
ArrayList<String> names = new ArrayList<String>();
try {
names = data.getDoctorlistDB(getActivity());
} catch (SQLException e) {
e.printStackTrace();
}
listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.support_simple_spinner_dropdown_item, names);
// set the adapter
list.setAdapter(listAdapter);
return view;
}
}
*/
}
This is the activity icon text tabs layout file:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
This is my main activity layout file:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:id="#+id/btnIconTextTabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_icon_text_tabs"
android:textSize="15dp" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
This is my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onGeoLocationButtonClick"
android:text="Your Location" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onSubmitPriceClick"
android:text="Submit a price" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onScrollViewButtonClick"
android:text="Scrollview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onWebViewButtonClick"
android:text="Webview" />
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is my Fragment one layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onGeoLocationButtonClick"
android:text="Your Location" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onSubmitPriceClick"
android:text="Submit a price" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onScrollViewButtonClick"
android:text="Scrollview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onWebViewButtonClick"
android:text="Webview" />
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I would like to display the entered list items - this whole processus is working well - in fragment One, but the list items are not showing up. I don´t get any errors so I´m a bit stuck here. Any help or hints would be very appreciated, thanks.

Categories

Resources