Why isn't my listview updating? - java

I've got a problem with my listview. When I press a button it should add an item to a listview, but it doesn't. I've used a Toast to be sure that the onClick event for the button is good. Can anyone help me ?
This is the fragment's java code.
package com.wordpress.softwarebycs.i_cseditor;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Cosmin on 11.04.2015.
*/
public class code_Fragment extends Fragment implements AdapterView.OnItemSelectedListener{
View rootview;
WebView previewBrowser;
EditText codebox,fname;
Button save_btn;
Spinner spinner;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> list_adapter;
ListView projects;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
rootview = inflater.inflate(R.layout.code_layout,container, false);
previewBrowser = (WebView)rootview.findViewById(R.id.previewBrowser);
codebox= (EditText)rootview.findViewById(R.id.codebox);
projects=(ListView)rootview.findViewById(R.id.projectsListView);
list_adapter=new ArrayAdapter<String>(rootview.getContext(), android.R.layout.simple_list_item_1, list);
projects.setAdapter(list_adapter);
list.clear();
save_btn=(Button)rootview.findViewById(R.id.save_btn);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeFile();
}
});
fname=(EditText)rootview.findViewById(R.id.fname);
spinner= (Spinner)rootview.findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(rootview.getContext(),R.array.spinner_items,android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final TabHost tabHost=(TabHost)rootview.findViewById(R.id.tabHost);
tabHost.setup();
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
String file="i_C_s_editor_temp_file_ne_trebuie_un_nume_lung_tare_de_tot.html";
try {
FileOutputStream fos = getActivity().openFileOutput(file, Context.MODE_PRIVATE);
fos.write(codebox.getText().toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
previewBrowser.loadUrl("file:///data/data/com.wordpress.softwarebycs.i_cseditor/files/"+file);
}
});
TabHost.TabSpec spec1=tabHost.newTabSpec("Code");
spec1.setContent(R.id.codeTab);
spec1.setIndicator("Code");
TabHost.TabSpec spec2=tabHost.newTabSpec("Preview");
spec2.setContent(R.id.previewTab);
spec2.setIndicator("Preview");
TabHost.TabSpec spec3=tabHost.newTabSpec("File");
spec3.setContent(R.id.fileTab);
spec3.setIndicator("File");
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
tv.setTextColor(Color.parseColor("#ffe0e0e0"));
}
projects.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) {
TextView clickedView = (TextView) view;
readFile(clickedView.getText().toString());
//tabHost.setCurrentTab(0);
}
});
return rootview;
}
public void writeFile()
{
String FILE_NAME=fname.getText().toString()+spinner.getSelectedItem().toString();
try {
FileOutputStream fos = getActivity().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(codebox.getText().toString().getBytes());
list.add(FILE_NAME);
Toast toast = Toast.makeText(rootview.getContext(),
"File saved!",
Toast.LENGTH_SHORT);
toast.show();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void actionStopped(){
try {
FileOutputStream fos = getActivity().openFileOutput("cfg2.txt", Context.MODE_PRIVATE);
Integer k;
for(k=0;k<list.size();k++)
{fos.write(list.get(k).toString().getBytes());
fos.write(System.getProperty("line.separator").getBytes());}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void actionResummed() {
list.clear();
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput("cfg2.txt")));
String line;
while ((line = bReader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
actionResummed();
}
#Override
public void onPause() {
super.onPause();
actionStopped();
}
public void readFile(String path)
{
codebox.setText("");
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(getActivity().openFileInput(path)));
String line;
while ((line = bReader.readLine()) != null) {
codebox.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the fragment's xml
<?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: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"
android:background="#ff666666">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ff8a3e6b">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/codeTab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/codebox"
android:gravity="top|left"
android:background="#ffffffff"
android:scrollbars="vertical|horizontal"/>
</LinearLayout>
<LinearLayout
android:id="#+id/previewTab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/previewBrowser"
android:scrollbars="vertical|horizontal"
></WebView>
</LinearLayout>
<!--fileTab-->
<LinearLayout
android:id="#+id/fileTab"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff666666"
android:orientation="vertical"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:layout_marginBottom="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="File&apos;s Name"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal"
android:textColor="#ffe0e0e0"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout2">
<EditText
android:layout_width="237dp"
android:layout_height="41dp"
android:id="#+id/fname"
android:layout_marginTop="10dp"
android:background="#ff8a3e6b"
android:textColor="#ffe0e0e0" />
<Spinner
android:layout_width="fill_parent"
android:layout_height="41dp"
android:id="#+id/spinner"
android:background="#ff8a3e6b"
android:layout_marginTop="9dp"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout3">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save File"
android:id="#+id/save_btn"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:background="#ff8a3e6b"
android:textColor="#ffe0e0e0"
/>
</LinearLayout>
<!-- separator-->
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:id="#+id/separator"
android:background="#ff8a3e6b"
android:layout_marginTop="5dp" />
<!--open file -->
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/separator"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout4">
<TextView
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text2"
android:textSize="25dp"
android:text="Select file to open!"
android:layout_gravity="top|center"
/>
<ListView
android:layout_width="fill_parent"
android:layout_below="#+id/text2"
android:layout_height="fill_parent"
android:id="#+id/projectsListView"
android:scrollbars="vertical|horizontal"
android:background="#ff8a3e6b">
</ListView>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>

To update listview you have to notify it, I don't see notifying method in your click method
Add below code in
save_btn.setOnClickListener //Method after calling to writeFile() Method
list_adapter.notifyDataSetChanged();

Related

ViewPager2 with RecyclerView not displaying correctly

I've been working on an app that uses a vertical RecyclerView inside a fragment, all inside a ViewPager2 object with a tabLayout. I can't seem to figure out how to make all these things work together. Currently, it looks like I got it to show the recycler view with the data but the tabs aren't showing up and the items in the list are spaced like they're different pages. Could someone explain how I'm messing up?
It looks like this:
I'd like it to be like this:
Here's the code so far:
Classes
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.Style;
public class MainActivity extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox Access token
Mapbox.getInstance(getApplicationContext(), getString(R.string.mapbox_api_key));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(mapboxMap -> mapboxMap.setStyle(Style.DARK, style -> {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}));
ViewPager2 pager = findViewById(R.id.view_pager);
ViewPageAdapter pageAdapter = new ViewPageAdapter(getSupportFragmentManager(), getLifecycle());
pager.setAdapter(pageAdapter);
pager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
TabLayout tabLayout = findViewById(R.id.tabLayout2);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
new TabLayoutMediator(tabLayout, pager,
(tab, position) -> {
switch (position) {
case 0:
tab.setText(getString(R.string.stats_tab));
break;
case 1:
tab.setText(getString(R.string.news_tab));
break;
case 2:
tab.setText(getString(R.string.symptoms_tab));
break;
case 3:
tab.setText(getString(R.string.safety_tab));
break;
default:
break;
}
}).attach();
// Get data
new StatsLoader("https://api.covid19api.com/summary", pageAdapter, pager).execute();
}
}
StatsFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
public class StatsFragment extends Fragment {
View view;
RecyclerView recyclerView;
JSONArray covidData;
public StatsFragment(JSONArray data) {
covidData = data;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_page, container, false);
recyclerView = view.findViewById(R.id.recyclerView2);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(false);
RecyclerView.Adapter<CustomListAdapter.ListViewHolder> mAdapter = new CustomListAdapter(covidData);
recyclerView.setAdapter(mAdapter);
return view;
}
}
StatsLoader.java
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public class StatsLoader extends AsyncTask<String, Void, JSONArray> {
Exception exception;
String urlString = "";
static JSONArray covidData = new JSONArray();
ViewPageAdapter pageAdapter;
public StatsLoader(String url, ViewPageAdapter adapter) {
super();
urlString = url;
pageAdapter = adapter;
}
#Nullable
#Override
public JSONArray doInBackground(String ... urls) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
covidData = json.getJSONArray("Countries");
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i < covidData.length(); i++) {
list.add(covidData.get(i));
}
SortJsonArray sortJsonArray = new SortJsonArray();
sortJsonArray.sortArray(list, "TotalConfirmed", false);
covidData = new JSONArray();
for (Object object : list) {
covidData.put(object);
}
return covidData;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(JSONArray coviddata) {
if (this.exception == null) {
Log.d("Check", "Works!");
pageAdapter.addFragment(new StatsFragment(coviddata), "Stats");
}
}
}
Layouts
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:statusBarScrim="#null"
app:titleEnabled="false"
android:minHeight="?attr/actionBarSize" >
<fragment
android:id="#+id/mapView"
android:name="com.mapbox.mapboxsdk.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="350sp"
android:apiKey="#string/mapbox_api_key"
android:clickable="true"
android:enabled="true"
android:focusable="true"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginBottom="48dp"
android:gravity="top"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark"
app:title="" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/view_page" >
</androidx.viewpager2.widget.ViewPager2>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
view_page
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
tools:listitem="#layout/list_view">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
list_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="14sp"
android:layout_margin="15sp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40sp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/name"
android:layout_toStartOf="#+id/name"
android:contentDescription="Image of country flag" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10sp" />
<TextView
android:id="#+id/cases"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
for tablayout :
take/make tablayout outside the CollapsingToolbarLayout
and for "list are spaced" :
make wrap_content height in view_page code
also list_view LinearLayout height to wrap_content
hope it helped :)
In your list_view , Use your parent layout height wrap_content not match_parent
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="14sp"
android:layout_margin="15sp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40sp">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/name"
android:layout_toStartOf="#+id/name"
android:contentDescription="Image of country flag" />
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10sp" />
<TextView
android:id="#+id/cases"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name" />
</RelativeLayout>
</androidx.cardview.widget.CardView>

Android: onItemClick and onItemLongClick do not respond

My Android app is composed of an SQLite database which populates individual ListView items with data user saves. Those items are available for display in activity_main.xml.
I have a class called RecordsListFragment which contains the two problematic methods: onItemClick and onItemLongClick. Here is the class in its entirety:
package com.example.benignfella.projectworkinghoursapplication.Fragment;
import android.app.Activity;
import android.os.AsyncTask;
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.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.example.benignfella.projectworkinghoursapplication.R;
import com.example.benignfella.projectworkinghoursapplication.Adapter.RecordsListAdapter;
import com.example.benignfella.projectworkinghoursapplication.Database.RecordsDAO;
import com.example.benignfella.projectworkinghoursapplication.GetSet.Records;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class RecordsListFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {
public static final String ARGUMENT_ITEM_ID = "records_list";
Activity activity;
ListView recordsListView;
ArrayList<Records> records;
RecordsListAdapter recordsListAdapter;
RecordsDAO recordsDAO;
private GetRecordsTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
recordsDAO = new RecordsDAO(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_records_list, container, false);
findViewsById(view);
task = new GetRecordsTask(activity);
task.execute((Void) null);
return view;
}
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Records record = (Records) parent.getItemAtPosition(position);
if (records != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedRecord,", record);
CustomRecordsDialogFragment customRecordsDialogFragment = new CustomRecordsDialogFragment();
customRecordsDialogFragment.setArguments(arguments);
customRecordsDialogFragment.show(getFragmentManager(), CustomRecordsDialogFragment.ARGUMENT_ITEM_ID);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Records records = (Records) parent.getItemAtPosition(position);
recordsDAO.deleteRecord(records);
recordsListAdapter.remove(records);
return true;
}
public class GetRecordsTask extends AsyncTask<Void, Void, ArrayList<Records>> {
private final WeakReference<Activity> activityWeakRef;
public GetRecordsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected ArrayList<Records> doInBackground(Void... arg0) {
ArrayList<Records> recordsArrayList = recordsDAO.getRecords();
return recordsArrayList;
}
#Override
protected void onPostExecute(ArrayList<Records> empList) {
if (activityWeakRef.get() != null && !activityWeakRef.get().isFinishing()) {
records = empList;
if (empList != null) {
if (empList.size() != 0) {
recordsListAdapter = new RecordsListAdapter(activity, empList);
recordsListView.setAdapter(recordsListAdapter);
} else {
Toast.makeText(activity, "No Records about records... wait wot m8?",
Toast.LENGTH_LONG).show();
}
}
}
}
}
public void updateView() {
task = new GetRecordsTask(activity);
task.execute((Void) null);
}
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
Here is activity_main.xml with FrameLayout:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Layout resource file which contains a ListView is called fragment_records_list.xml and here it is:
<?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"
android:background="#f9f9f9">
<ListView
android:id="#+id/list_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay"/>
</RelativeLayout>
Lastly, there is a resource file containing the layout of a single item, list_item.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"
android:background="#ededed"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/layout_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_record_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="ID"
android:textSize="20dp"/>
<TextView
android:id="#+id/text_record_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_id"
android:padding="5dp"
android:text="Date"
android:textColor="#00942b"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_date"
android:drawableStart="#drawable/ic_date_range_black_24dp"
android:padding="5dp"
/>
<TextView
android:id="#+id/text_record_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_id"
android:padding="5dp"
android:text="Description"
/>
<TextView
android:id="#+id/text_record_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:padding="5dp"
android:text="17:00"
android:textSize="16dp"
android:textColor="#004561"
/>
<TextView
android:id="#+id/text_record_dash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_start"
android:padding="5dp"
android:text="-"
android:textSize="16dp"
/>
<TextView
android:id="#+id/text_record_finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_dash"
android:padding="5dp"
android:text="20:00"
android:textSize="16dp"
android:textColor="#c7002a"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_finish"
android:drawableStart="#drawable/ic_timer_black_24dp"
/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/layout_item"
android:background="#000000"
/>
</RelativeLayout>
I haven't found a definite answer to my question, so I'm asking for a bit of help here.
You need set OnItemClickListener and OnLongItemClickListener to ListView, I edited your method in the initializing variable ListView:
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
recordsListView.setOnItemClickListener(this);
recordsListView.setOnItemLongClickListener(this);
}

display album art using mediametadataretriever

okay so I am trying to display album art for songs in my app . I am trying to do it by using Mediametadataretriever. But I am getting an IllegalStateException in line metaRetriver.setDataSource(Environment.getExternalStorageDirectory().getPath() );
I understand it might be because of using an invalid path but I can't figure out what is the valid path then . I am really newbie to android app development. Can anyone help me with it ?
PlayListActivity.java :
package com.example.dell_1.myapp3;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.IOException;
public class PlayListActivity extends Activity {
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv();
}
public void acv() {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(Environment.getExternalStorageDirectory().getPath() );
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart);
}
}
activity_play_list.xml :
<?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="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
activity_android_building_music_player.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"
>
<LinearLayout
android:id="#+id/player_header_bg"
android:layout_width="fill_parent"
android:layout_height="60dip"
android:layout_alignParentTop="true"
android:background="#layout/bg_player_header"
android:paddingLeft="5dp"
android:paddingRight="5dp">
<TextView
android:id="#+id/songTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:paddingLeft="50dp"
android:text="The Good"
android:textColor="#04b3d2"
android:textSize="16dp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/btnPlaylist"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#null"
android:src="#drawable/btn_playlist" />
</LinearLayout>
<LinearLayout
android:id="#+id/songThumbnail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/player_header_bg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<ImageView
android:id="#+id/coverart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/player_footer_bg"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#layout/bg_player_footer"
android:gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="1">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.40"
android:layout_alignParentLeft="true"
android:paddingLeft="10dp"
android:background="#null"
android:src="#drawable/btn_previous" />
<ImageButton
android:id="#+id/btnPlay1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#null"
android:src="#drawable/btn_play"
android:onClick="buttonAction1"/>
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="250dp"
android:background="#null"
android:src="#drawable/btn_next" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<SeekBar
android:id="#+id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/player_footer_bg"
android:layout_alignLeft="#+id/timerDisplay"
android:layout_alignStart="#+id/timerDisplay"
android:layout_marginBottom="10dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:progressDrawable="#drawable/seekbar_progress"
android:thumb="#drawable/download8" />
<LinearLayout
android:id="#+id/timerDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/songProgressBar"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<TextView
android:id="#+id/songCurrentDurationLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:textColor="#eeeeee"
android:textStyle="bold" />
<TextView
android:id="#+id/songTotalDurationLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textColor="#04cbde"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/timerDisplay"
android:gravity="center">
<ImageButton
android:id="#+id/btnRepeat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#null"
android:src="#drawable/btn_repeat" />
<ImageButton
android:id="#+id/btnShuffle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#null"
android:src="#drawable/btn_shuffle" />
</LinearLayout>
</RelativeLayout>
Actually you are playing some some in one file path and you are trying to fetch the art from external storage file path, so you should send the path to that method,
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
}
}
And few suggestions,
You should not use setContentView multiple time in an activity I understand you are using 2 layouts, but in that case, you should use 2 different activity.
You playing something songs and user will not be in your app always they like to move around the application so try to use service to run the song in background
For more reference, you can get fantastic opensource app will be available in Github look into that.
Well you are trying to get a thumbnail from a specific file, but you are putting in the path of the External Storage Directory. So by using
metaRetriver.setDataSource(Environment.getExternalStorageDirectory().getPath() );
You are pointing to a folder, not a specific media file. But this:
metaRetriver.setDataSource(Environment.getExternalStorageDirectory().getPath() + "yourFileName.mp3" );
Is more in line with what you would need.

TextView in ScrollView not updating

I create textView in scrollView. Every time i setText the textView, the text not updating, but when i open the keyboard then close it, the text updated..
after googling, i got the solution is call textView.invalidate() and textView.requestLayout(). But i am currious why it's not updating without call invalidate and requestLayout? Is scrollView has somethis 'special' so i need to call invalidate and requestLayout?
here is the code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.zihadrizkyef.belajarinternalstorage.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical">
<EditText
android:id="#+id/etWrite"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:gravity="top"
android:hint="write text here"/>
<View android:id="#+id/separator1"
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:background="#aaa"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="#+id/tvRead"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:hint="(no text)"/>
</ScrollView>
<View android:id="#+id/separator2"
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:background="#aaa"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="2"
android:gravity="center">
<Button
android:id="#+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:onClick="onClick"
android:text="save"/>
<Button
android:id="#+id/btnLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:onClick="onClick"
android:text="load"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.zihadrizkyef.belajarinternalstorage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private final String FNAME = "mydata";
EditText etWrite;
TextView tvRead;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etWrite = (EditText)findViewById(R.id.etWrite);
tvRead = (TextView)findViewById(R.id.tvRead);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnSave:
String data = etWrite.getText().toString();
try {
FileOutputStream fOut = openFileOutput(FNAME, MODE_PRIVATE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(MainActivity.this, "File saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.btnLoad:
int cRead;
String read="";
try {
FileInputStream fIn = openFileInput(FNAME);
while((cRead=fIn.read())!=-1) {
read += Character.toString((char)cRead);
}
tvRead.setText(read);
tvRead.invalidate();
tvRead.requestLayout();
Toast.makeText(MainActivity.this, "File loaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
github : https://github.com/zihadrizkyef/FileWriteRead_InternalStorage
You can try updating the value using AsyncTask. As the method onPostExecute() runs in UI thread, it can make any kind of UI updates dynamically. Refer to this for more info:https://developer.android.com/reference/android/os/AsyncTask.html
you've set ScrollView's height and TextView's height to "0" and don't have any text set for TextView,so you have to invalidate your view in order to measure its layout parameters again.
you can use this link:
Making TextView scrollable on Android
Its obvious,
Whenever you change the data for a control it doesn't get reflected in the view, unless the control or its parent control or view is invalidated.
Its also mentioned in documentation of TextView
https://developer.android.com/reference/android/widget/TextView.html#setText(char[], int, int)

android null object reference, despite being present

I have an MainActivity that basically has a framelayout that has different fragments sitting it in depending on what the user is doing.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical" tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#27b"
android:layout_weight=".04">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/activity_main_framelayout">
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".9"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1B5F96"
android:layout_weight=".9"
android:id="#+id/activity_main_status_title"
android:text="#string/activity_main_status_title"
tools:ignore="NestedWeights" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#AD3333"
android:layout_weight=".15"
android:id="#+id/activity_main_status_value"
android:text="#string/activity_main_status_value"/>
</LinearLayout>
</LinearLayout>
The problem starts with an interface method void WillYouAccept(final String caller)
#Override
public void WillYouAccept(final String caller) {
Connection f = new Connection();
ShiftView(f);
runOnUiThread(new Runnable() {
#Override
public void run() {
Connection b = (Connection) getFragmentManager().findFragmentById(R.layout.connection_display);
b.updateInitiator(caller);
}
});
}
The line b.updateInitiator(caller); is what initiates the null object reference error. ShiftView has basically been swapping out fragments into the framelayout for me, and so far has worked well.
#Override
public void ShiftView(Object obj) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.activity_main_framelayout, (Fragment) obj);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
Basically a textview in connection_display.xml(Connection.java) needs to be updated from the MainActivity, and somehow initiator = (TextView) view.findViewById(R.id.textView_connection_display_initiator_ID); is null when it is being interacted with from MainActivity.
Connection.java
package "";
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class Connection extends Fragment {
MiddleMan mCallBack;
Button accept;
Button deny;
TextView initiator;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallBack = (MiddleMan) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement ReqestConnect");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_display, container, false);
mCallBack.DisplayHome();
initiator = (TextView) view.findViewById(R.id.textView_connection_display_initiator_ID);
accept = (Button) view.findViewById(R.id.button_connection_display_ACCEPT);
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonAccept();
}
});
deny = (Button) view.findViewById(R.id.button_connection_display_DENY);
deny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonDeny();
}
});
return view;
}
private void buttonAccept() {
System.out.println("Accept Button Pressed");
}
private void buttonDeny() {
System.out.println("Deny Button Pressed");
}
public void updateInitiator(final String s) {
initiator.setText(s);
}
}
connection_display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/textView_connection_display_title"
android:id="#+id/textView_connection_display_title" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_marginTop="45dp"
android:layout_weight=".004">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_connection_display_ID_label"
android:id="#+id/textView_connection_display_ID_label" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView_connection_display_initiator_ID"
android:text="#string/textView_connection_display_initiator_ID" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight=".004">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/textView_connection_display_exp"
android:id="#+id/textView_connection_display_exp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight=".04">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="#string/button_connection_display_ACCEPT"
android:id="#+id/button_connection_display_ACCEPT"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_connection_display_DENY"
android:id="#+id/button_connection_display_DENY"
tools:ignore="ButtonStyle" />
</LinearLayout>
</LinearLayout>
b was definitely turning up as null, however the bit above had always found the fragment, so I solved it with this:
#Override
public void WillYouAccept(final String caller) {
final Connection f = new Connection();
ShiftView(f);
runOnUiThread(new Runnable() {
#Override
public void run() {
f.updateInitiator(caller);
}
});
}

Categories