Can't populate ListView on fragment using Json - android-fragments

Hi there! I am working on an application in which I need to populate a ListView from Mysql database.This populated list must be shown on a fragment.
public class AppsTabFragment extends ListFragment
{
private ProgressDialog pdialog;
ListView listView;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String,String>> appslist;
public String url_all_apps="http://10.0.2.2/sisoft/get_all_apps.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_APPS = "appname";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "appname";
MainActivity main=new MainActivity();
// products JSONArray
JSONArray apps = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.apps_tab_fragment, container, false);
listView = (ListView) view.findViewById(android.R.id.list);
listView = getListView();
return view;
}
#Override
public void onViewCreated(View view,Bundle SavedInstanceState)
{
appslist = new ArrayList<HashMap<String,String>>();
new loadAllApps().execute();
}
class loadAllApps extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage("Loading apps. Please wait...");
pdialog.setIndeterminate(false);
pdialog.setCancelable(true);
pdialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jparser.makeHttpRequest(url_all_apps, "GET", params);
// Check your log cat for JSON response
Log.d("All apps: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
apps = json.getJSONArray(TAG_APPS);
// looping through All Products
for (int i = 0; i < apps.length(); i++) {
JSONObject c = apps.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
appslist.add(map);
}
} else {
// no apps found
// Launch Add New product Activity
getActivity().finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pdialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), appslist,
R.layout.list_apps, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.id, R.id.appname });
// updating listview
listView.setAdapter(adapter);
}
});
}
}
}
This is my LogCat showing errors.
06-06 06:12:43.834: D/dalvikvm(862): GC_CONCURRENT freed 72K, 8% free 2781K/2996K, paused 14ms+22ms, total 172ms
06-06 06:12:44.344: D/AndroidRuntime(862): Shutting down VM
06-06 06:12:44.344: W/dalvikvm(862): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-06 06:12:44.454: E/AndroidRuntime(862): FATAL EXCEPTION: main
06-06 06:12:44.454: E/AndroidRuntime(862): java.lang.IllegalStateException: Content view not yet created
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
06-06 06:12:44.454: E/AndroidRuntime(862): at com.sisoft.sisoftstore.fragment.AppsTabFragment.onCreateView(AppsTabFragment.java:45)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1374)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.View.measure(View.java:15518)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.View.measure(View.java:15518)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.View.measure(View.java:15518)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.View.measure(View.java:15518)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-06 06:12:44.454: E/AndroidRuntime(862): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.View.measure(View.java:15518)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.Choreographer.doFrame(Choreographer.java:532)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.os.Handler.handleCallback(Handler.java:725)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.os.Handler.dispatchMessage(Handler.java:92)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.os.Looper.loop(Looper.java:137)
06-06 06:12:44.454: E/AndroidRuntime(862): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-06 06:12:44.454: E/AndroidRuntime(862): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 06:12:44.454: E/AndroidRuntime(862): at java.lang.reflect.Method.invoke(Method.java:511)
06-06 06:12:44.454: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-06 06:12:44.454: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-06 06:12:44.454: E/AndroidRuntime(862): at dalvik.system.NativeStart.main(Native Method)
06-06 06:17:44.713: I/Process(862): Sending signal. PID: 862 SIG: 9
It shows an error at line listView = getListView();. But when I remove this line, it shows an error like this.
06-06 07:04:06.705: E/AndroidRuntime(1753): java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Can anyone help me in solving this issue? I would be very thankful if anybody helps me in solving this issue.

In your xml, set your list id to
#android:id/list
And then just use:
listView = getListView();
Without:
listView = (ListView) view.findViewById(android.R.id.list);

Related

HttpSessionBindingListener.valueUnbound is not triggered on session timeout

We need to do some DB cleanup on session timeout, so implemented HttpSessionBindingListener and added an object to session on user login, we never remove it from session explicitly.
HttpSessionBindingListener.valueUnbound is triggered if we manually call session.invalidate but the problem is it doesn't get triggered on session timeout. I see an error in the console but not sure what the problem is.
Set the object into session on login and invalidate session on logout:
#Named("logincontroller")
#Stateful
public class LoginController implements ILoginController, Serializable {
#Inject
private Credentials credentials;
private ExternalContext ec = null;
private HttpServletRequest request =null;
private HttpServletResponse response=null;
private HttpSession session=null;
#PostConstruct
private void getLocalVariables() {
ec = FacesContext.getCurrentInstance().getExternalContext();
request= (HttpServletRequest)ec.getRequest();
session = request.getSession();
}
#Override
public boolean login() {
...
credentials.setUserName(getUserName().toUpperCase());
credentials.setUserPassword(getPassword());
// set the object into session on user login
session.setAttribute("credentials", credentials);
}
#Override
public void logout() {
...
try {
response.sendRedirect(path+"/faces/Exit.html");
// invalidate the session on logout
session.invalidate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Credentials object implementing HttpSessionBindingListener
#Named("credentials")
#SessionScoped
public class Credentials implements ICredentials, Serializable, HttpSessionBindingListener {
...
#Override
public void valueBound(HttpSessionBindingEvent event) {
//do nothing
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
try {
// run DB scripts to clean up
lockManager.releaseAllLocksForUser(getUserName().toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Stacktrace:
15:13:03,252 INFO [org.jboss.as.repository] (ServerService Thread Pool -- 66) WFLYDR0009: Content C:<path>jbossstudio10\runtimes\jboss-eap\standalone\data\content\62\7ccffda3936daab4d3148eb2e51584f8372592 is obsolete and will be removed
15:13:03,299 INFO [org.jboss.as.repository] (ServerService Thread Pool -- 66) WFLYDR0002: Content removed from location C:\<path>\jbossstudio10\runtimes\jboss-eap\standalone\data\content\62\7ccffda3936daab4d3148eb2e51584f8372592\content
15:26:36,245 ERROR [stderr] (default task-22) Exception in thread "default task-22" org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.SessionScoped
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:689)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:90)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstanceStrategy$CachingContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:165)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstance.getIfExists(ContextualInstance.java:63)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:83)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.proxy.ProxyMethodHandler.getInstance(ProxyMethodHandler.java:125)
15:26:36,246 ERROR [stderr] (default task-22) at com.facility.security.Credentials$Proxy$_$$_WeldClientProxy.valueUnbound(Unknown Source) // unknown source??
15:26:36,246 ERROR [stderr] (default task-22) at io.undertow.servlet.core.SessionListenerBridge.attributeRemoved(SessionListenerBridge.java:132)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.SessionListeners.attributeRemoved(SessionListeners.java:81)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl.removeAttribute(InMemorySessionManager.java:500)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.servlet.core.SessionListenerBridge.sessionDestroyed(SessionListenerBridge.java:72)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.SessionListeners.sessionDestroyed(SessionListeners.java:61)
15:26:36,248 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl.invalidate(InMemorySessionManager.java:528)
15:26:36,248 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1.run(InMemorySessionManager.java:357)
15:26:36,248 ERROR [stderr] (default task-22) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
15:26:36,248 ERROR [stderr] (default task-22) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
15:26:36,248 ERROR [stderr] (default task-22) at java.lang.Thread.run(Thread.java:748)
Do I need to get a new session in valueUnbound to run my DB scripts? I thought that we still have session when valueUnbound is called. I did search stackoverflow but to no avail.
Any help is greatly appreciated.
Env: Windows 7 Enterrpise, JDK 1.8, JBoss EAP 7.0.0, CDI 1.2, Mojarra 2.2.12-jbossorg-2, deltaspike 1.8.1, Servlets 3.1, PrimeFaces 6.1, Oracle 11g
I've never really worked with HttpSessionBindingListener.valueUnbound, but it looks like the ordering of events is a bit jumbled between CDI and servlet behaviour. Specifically it looks like CDI is told to tear down session beans before HttpSessionBindingListener.valueUnbound is invoked. Hence the exception - when the method should be invoked, you no longer have session context active.
Possible solution is to twist your code around and not use HttpSessionBindingListener.valueUnbound and instead make Credentials.valueUnbound a #PreDestroy method. That way it should be invoked by CDI whenever that bean is going to be destroyed, no matter if the cause is session invalidation or timeout.

Calling Fragment from RecyclerView Adapter

I have a recyclerView that shows a list in cardView. This recyclerview is located in one fragment that shown in a viewPager tab. I want to go to new Fragment when thumbnail in cardview is clicked.
I implemented following onBindViewHolder in order to have this functionality:
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment productDetailFragment = new ProductDetailFragment();
(FragmentActivity)mContext).getSupportFragmentManager().beginTransaction()
.replace(R.id.grid_page_recycler_view, productDetailFragment).commit();
}
});
But after running, it returns:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.support.v7.widget.RecyclerView.findMinMaxChildLayoutPositions(RecyclerView.java:3757)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3494)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3019)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:666)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15819)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15819)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
at android.view.View.measure(View.java:15819)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1965)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1146)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1356)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1046)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4603)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
What's the reason? It's notable that if I want to call another activity, it is easy to implement.
Thanks.
And I must say that there are several similar questions here, but I could not use them.
Create one method for replacing fragment in your MAinActivity.
Take ViewPager in a Fragment and push it from MainActivity.
Now Call replace fragment method in your recyclerView Adapter.
public void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.frame_container, fragment, backStateName);
ft.addToBackStack(backStateName);
ft.commit();
}
}

New Activity from FloatingActionButton

i would launch an activity with a click in a floating action button, but when i click this, I get "Unfortunately, ... has stopped.". please help me!
questo è il codice del bottone di default, and this works
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
When change the code of a snackbar with the code of a new activity, this does not work
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity=new Intent (getApplicationContext(),add.class);
startActivity(launchactivity);
}
});
This is my logcat
09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fra31.tradebooks, PID: 6353
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.fra31.tradebooks.add.onCreate(add.java:47)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5289) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115) 
you should try this.
Intent launchactivity = new Intent(MainActivity.this, add.class);
startActivity(launchactivity);
Intent launchactivity=new Intent (MainActivity.this,add.class);
startActivity(launchactivity);
and you should go to androidmanifest.xml and define your activity as this :
<activity android:name=".MainActivity">
</activity>

updating array adapter onActivityResult after getting data from dialogfragment

My dilema is that i am coming from a dialogfragment to my weighInFragment with two pieces of information: a date and an int. I want to be able to use these two pieces of information and construct a newEntry which needs to be added to an existing Arrayadapter. The arraylist is displayed on the weighInFragment and i use the dialogfragment to capture information for new entries. However, when i try to add the new entry to the adapter i get a nullpointer exception which i believe is due to the adapter being null. So i am wondering how could i get this adapter and be able to add the new entry?
Here is y onActivityResult which is where i land after i hit "save" on my dialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DATEPICKER_FRAGMENT:
if (resultCode == Activity.RESULT_OK) {
Bundle bundle=data.getExtras();
Date date = (Date) bundle.getSerializable("date");
int weight = (Integer) bundle.getSerializable("weight");
Log.d("NewEntry", "Date is: " + date + "Weight: " +weight );
WeighInAdapter adapter = (WeighInAdapter)getListAdapter();
WeighInEntry newEntry = new WeighInEntry();
newEntry.setDate(date);
newEntry.setWeight(weight);
adapter.add(newEntry);
adapter.notifyDataSetChanged();
} else if (resultCode == Activity.RESULT_CANCELED){
}
break;
}
}
This is where i get my data in the dialogadapter:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
// LayoutInflater inflater = getActivity().getLayoutInflater();
final View v = getActivity().getLayoutInflater()
.inflate(R.layout.weigh_in_dialog, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatePicker datePicker = (DatePicker)v.findViewById(R.id.datePicker1);
EditText weightAmount = (EditText) v.findViewById(R.id.weight);
mDate = getDateFromDatePicket(datePicker);
mWeight = Integer.parseInt(weightAmount.getText().toString());
Intent i = new Intent();
Bundle extras=new Bundle();
extras.putSerializable("date", mDate); //putString("date",Month);
extras.putInt("weight",mWeight);
i.putExtras(extras);
getTargetFragment().onActivityResult(getTargetRequestCode(),Activity.RESULT_OK,i);
dismiss() ;
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NewEntryDialogFragment.this.getDialog().cancel();
Log.d("CANCEL WAS PRESSED:", "!!!!!!!!!!!!");
}
});
return builder.create();
}
This is the logcat error:
11-17 17:42:51.050: D/NewEntry(2593): Date is: Tue Nov 17 17:42:51 EST 2015Weight: 200
11-17 17:42:51.060: D/AndroidRuntime(2593): Shutting down VM
11-17 17:42:51.060: W/dalvikvm(2593): threadid=1: thread exiting with uncaught exception (group=0xb1ae9b90)
11-17 17:42:51.070: E/AndroidRuntime(2593): FATAL EXCEPTION: main
11-17 17:42:51.070: E/AndroidRuntime(2593): Process: edu.bu.juanl.finalproject, PID: 2593
11-17 17:42:51.070: E/AndroidRuntime(2593): java.lang.NullPointerException
11-17 17:42:51.070: E/AndroidRuntime(2593): at edu.bu.juanl.finalproject.WeighInFragment.onActivityResult(WeighInFragment.java:141)
11-17 17:42:51.070: E/AndroidRuntime(2593): at edu.bu.juanl.finalproject.NewEntryDialogFragment$1.onClick(NewEntryDialogFragment.java:84)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.os.Handler.dispatchMessage(Handler.java:102)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.os.Looper.loop(Looper.java:137)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-17 17:42:51.070: E/AndroidRuntime(2593): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 17:42:51.070: E/AndroidRuntime(2593): at java.lang.reflect.Method.invoke(Method.java:515)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-17 17:42:51.070: E/AndroidRuntime(2593): at dalvik.system.NativeStart.main(Native Method)
11-17 17:42:53.440: I/Process(2593): Sending signal. PID: 2593 SIG: 9
ive tried multiple things and i cant figure it out!
The DialogPickerFragment inputs data from the user and this needs to be reflected in a different dialog fragment that contains a listview.
The data is being passed to the parent activity and it is trying to access an element belonging to the listview fragment. Herein lies the problem. The activity will not have access to the fragments list adapter.
What you should instead do is implement an interface between the activity and the listview fragment and pass in the data.Check out the android developer guide: http://developer.android.com/training/basics/fragments/communicating.html

I can't reading SQLite Database by cursor. It is always crashing

Why does this code crash?
CustomDatabaseHelper.java:
public class CustomDatabaseHelper {
SQLiteDatabase db;
private static final String DATABASE_TABLE = "tbl_homework";
public static final String KEY_TITLE = "hw";
public static final String KEY_ROWID = "id";
private final Context mCtx;
public Cursor executeSQLQuery(String query){
Cursor c = db.rawQuery(query,null);
return c;
}
public Cursor fetchAllNotes() {
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE}, null, null, null, null, null);
}
public CustomDatabaseHelper(Context ctx) {
this.mCtx = ctx;
}
}
homework.java:
public class homework extends ListActivity {
SQLiteDatabase db;
private CustomDatabaseHelper mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homework);
//Create Database
db = openOrCreateDatabase("test_database.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
//Create table tbl_homework
final String CREATE_TABLE_HW =
"CREATE TABLE IF NOT EXISTS tbl_homework ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "hw TEXT);";
db.execSQL(CREATE_TABLE_HW);
press_cmd_back();
press_cmd_test_data();
mDbHelper = new CustomDatabaseHelper(this);
fillData();
}
//What will happen if cmd_back gets pressed
private void press_cmd_back(){
Button cmd_back = (Button)findViewById(R.id.cmd_back);
cmd_back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent Intent_main = new Intent(homework.this, Noten_HausaufgabenActivity.class);
startActivity(Intent_main);
}
});
}
//What will happen if cmd_test_data gets pressed
private void press_cmd_test_data(){
Button cmd_test_data = (Button)findViewById(R.id.cmd_eintragen);
cmd_test_data.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
open_database_rw();
EditText txt_hw = (EditText)findViewById(R.id.edt_eingabe);
String txt_insert_hw = txt_hw.getText().toString();
final String INSERT_HW = "INSERT INTO tbl_homework ('hw') VALUES ('" + txt_insert_hw + "')";
db.execSQL(INSERT_HW);
}
});
}
//Open Database RW
private void open_database_rw() {
db = SQLiteDatabase.openDatabase("/data/data/test.marco.notenha/databases/test_database.db",
null, SQLiteDatabase.OPEN_READWRITE);
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
/*startManagingCursor(c);
String[] from = new String[] { CustomDatabaseHelper.KEY_TITLE };
int[] to = new int[] {R.id.txt_notes_row};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);*/
}
}
Error log:
01-25 17:20:30.152: D/dalvikvm(7421): GC_EXTERNAL_ALLOC freed 48K, 50% free 2690K/5379K, external 0K/0K, paused 70ms
01-25 17:20:30.835: D/dalvikvm(7421): GC_EXTERNAL_ALLOC freed 32K, 49% free 2757K/5379K, external 203K/523K, paused 19ms
01-25 17:20:30.871: D/AndroidRuntime(7421): Shutting down VM
01-25 17:20:30.871: W/dalvikvm(7421): threadid=1: thread exiting with uncaught exception (group=0x4006f568)
01-25 17:20:30.871: E/AndroidRuntime(7421): FATAL EXCEPTION: main
01-25 17:20:30.871: E/AndroidRuntime(7421): java.lang.RuntimeException: Unable to start activity ComponentInfo{test.marco.notenha/test.marco.notenha.homework}: java.lang.NullPointerException
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.os.Handler.dispatchMessage(Handler.java:99)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.os.Looper.loop(Looper.java:130)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread.main(ActivityThread.java:3703)
01-25 17:20:30.871: E/AndroidRuntime(7421): at java.lang.reflect.Method.invokeNative(Native Method)
01-25 17:20:30.871: E/AndroidRuntime(7421): at java.lang.reflect.Method.invoke(Method.java:507)
01-25 17:20:30.871: E/AndroidRuntime(7421): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
01-25 17:20:30.871: E/AndroidRuntime(7421): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
01-25 17:20:30.871: E/AndroidRuntime(7421): at dalvik.system.NativeStart.main(Native Method)
01-25 17:20:30.871: E/AndroidRuntime(7421): Caused by: java.lang.NullPointerException
01-25 17:20:30.871: E/AndroidRuntime(7421): at test.marco.notenha.CustomDatabaseHelper.fetchAllNotes(CustomDatabaseHelper.java:22)
01-25 17:20:30.871: E/AndroidRuntime(7421): at test.marco.notenha.homework.fillData(homework.java:89)
01-25 17:20:30.871: E/AndroidRuntime(7421): at test.marco.notenha.homework.onCreate(homework.java:46)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-25 17:20:30.871: E/AndroidRuntime(7421): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
The app is crashing because of a null pointer in fetchAllNotes. This is happening because you aren't initializing db to anything inside CustomDatabaseHelper. You can try adding this line:
mDbHelper.db = db;
just before the call to fillData() in onCreate(). That should solve the null pointer exception. However, I think your code will have other problems if the data base already exists. You might want to take a look at the SQLiteOpenHelper class for a better way to do all this. (Also read the "Using Databases" section of the Data Storage guide topic.)

Resources