[Q] Beginning Programmer, need help with personal app - Android Software Development

I'm creating an app to keep track of all the messier objects in the sky. I have made a list view in the main activity that holds all the objects, when clicked it should open my other activity and display the objects info.
The program now goes to my second activity no matter what item i choose but doesn't change any of the TextView text without foreclosing.
also how can I recognize what object was clicked and change the information displayed for each object
The main Activity Java looks like this:
Code:
package com.kabluey.messier;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MessierCatalog extends ListActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set string array
setListAdapter(new ArrayAdapter<String>(this, R.layout.main, objects));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, change text in object info to clicked object name
TextView objText = (TextView) findViewById(R.id.txtObjName);
objText.setText(((TextView) view).getText());
Intent i = new Intent(MessierCatalog.this,Objectinfo.class);
startActivity(i);
}
});
}
static final String[] objects = new String[]
{
"m1", "m2","m3","m4","m5", "m6","m7","m8","m9","m10","m11","m12","m13","m14"
,"m15","m16","m17","m18","m19","m19","m20","m21","m22","m23","m24","m25","m26","m27","m28","m29","m30","m31","m32","m33"
,"m34","m35","m36","m37","m38","m39","m40","m41","m42","m43","m44","m45","m46","m47","m48","m49","m50","m51","m52","m53"
,"m54","m55","m56","m57","m58","m59","m60","m61","m62","m63","m64","m65","m66","m67","m68","m69","m70","m71","m72","m73"
,"m74","m75","m76","m77","m78","m79","m80","m81","m82","m83","m84","m85","m86","m87","m88","m89","m90","m91","m92","m93"
,"m94","m95","m96","m97","m98","m99","m100","m101","m102","m103","m104","m105","m106","m107","m108","m109","m110"
};
}
The second activity has no code in it now and is just an xml layout:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:src="@drawable/crab"
/>
<TableLayout
android:layout_width="fill_parent"
android:id="@+id/tableLayout1"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="Name of Object:"
android:padding="3dip"/>
<TextView
android:id="@+id/txtObjName"
android:text="Object name here"
android:padding="3dip"
android:paddingLeft="5dip" />
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TableRow>
<TableRow>
<TextView
android:text="Apparent Magnitude:"
android:padding="3dip"/>
<TextView
android:id="@+id/txtMagnitude"
android:paddingLeft="5dip"
android:text="9.0"/>
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TableRow>
</TableLayout>
</LinearLayout>

I think it may have to do with your casting of "view" to type "TextView" in you onItemClick override. I don't think the "View" passed to this override is a "TextView" is it? I would think it is the ListView to which you added the OnItemClickListener event handler.

Have some suggestion / tips:
1. This is more organized, also initializes first the Strings
Code:
package com.kabluey.messier;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MessierCatalog extends ListActivity
{
/** Called when the activity is first created. */
private static final String[] objects = {
"m1", "m2","m3","m4","m5", "m6","m7","m8","m9","m10","m11","m12","m13","m14"
,"m15","m16","m17","m18","m19","m19","m20","m21","m22","m23","m24","m25","m26","m27","m28","m29","m30","m31","m32","m33"
,"m34","m35","m36","m37","m38","m39","m40","m41","m42","m43","m44","m45","m46","m47","m48","m49","m50","m51","m52","m53"
,"m54","m55","m56","m57","m58","m59","m60","m61","m62","m63","m64","m65","m66","m67","m68","m69","m70","m71","m72","m73"
,"m74","m75","m76","m77","m78","m79","m80","m81","m82","m83","m84","m85","m86","m87","m88","m89","m90","m91","m92","m93"
,"m94","m95","m96","m97","m98","m99","m100","m101","m102","m103","m104","m105","m106","m107","m108","m109","m110"
};
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set string array
setListAdapter(new ArrayAdapter<String>(this, R.layout.main, objects));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, change text in object info to clicked object name
TextView objText = (TextView) findViewById(R.id.txtObjName);
objText.setText(((TextView) view).getText());
//Log here!, but im almost sure this is bad
Intent i = new Intent(MessierCatalog.this,Objectinfo.class);
startActivity(i);
}
});
}
2. Could you make a Log.i("APP", ((TextView) view).getText()) and upload output?. That appears like you're setting to your textview, the same text you got from it ( that's actually null / empty )
3. If output it's empty or not output, then this is the answer
Code:
package com.kabluey.messier;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MessierCatalog extends ListActivity
{
/** Called when the activity is first created. */
private static final String[] objects = {
"m1", "m2","m3","m4","m5", "m6","m7","m8","m9","m10","m11","m12","m13","m14"
,"m15","m16","m17","m18","m19","m19","m20","m21","m22","m23","m24","m25","m26","m27","m28","m29","m30","m31","m32","m33"
,"m34","m35","m36","m37","m38","m39","m40","m41","m42","m43","m44","m45","m46","m47","m48","m49","m50","m51","m52","m53"
,"m54","m55","m56","m57","m58","m59","m60","m61","m62","m63","m64","m65","m66","m67","m68","m69","m70","m71","m72","m73"
,"m74","m75","m76","m77","m78","m79","m80","m81","m82","m83","m84","m85","m86","m87","m88","m89","m90","m91","m92","m93"
,"m94","m95","m96","m97","m98","m99","m100","m101","m102","m103","m104","m105","m106","m107","m108","m109","m110"
};
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set string array
setListAdapter(new ArrayAdapter<String>(this, R.layout.main, objects));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// When clicked, change text in object info to clicked object name
TextView objText = (TextView) findViewById(R.id.txtObjName);
objText.setText(objects[position]);
Intent i = new Intent(MessierCatalog.this,Objectinfo.class);
startActivity(i);
}
});
}
Also for this cases it's not really needed TableRow, With a Relative layout it's enough, but I don't think that's a prob.
If you have some problem, feel free to contact me through PM.
Good luck, and cheers from colombia.
D4.

solved!
I searched the nets and found a solution, it seems to be working quite well.
thanks for all the help
My click listener now stores the value so both activities can access it
Code:
public void onItemClick(AdapterView<?> parent, View view,int position,long id)
{
Intent i = new Intent(MessierCatalog.this,Objectinfo.class);
//Get ListViews text and store it to "myText"
i.putExtra("myText", (((TextView) view).getText()));
startActivity(i);
}
The ObjectInfo activity now has code to store the ListViews text in String Variable and then set the text..
Code:
public class Objectinfo extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.objectinfo);
TextView objName = (TextView) findViewById(R.id.txtObjName);
//store ListViews Text to String
String str = getIntent().getStringExtra("myText");
//Set text to stored ListView string
objName.setText(str);
}
}

Related

webview help

I am having trouble creating a webview app for my already mobile ready site.
I keep getting this error in the emulator:
The application window cleaning forums (process com.windowcleaningforums) has stopped unexpectadly
The app never actualy loads just goes straight to this.
Basically i already have my sites mobile ready and browsing to them on your mobile works fine, but would like to put these into apps.
With a back, forward and refresh button when hitting menu button on phone.
(I am not sure what i need to add these yet but any advice would be great)
My project is set as bellow
Application name: Window Cleaning Forums
Package name: com.windowcleaningforums
Create activity: windowcleaningforums
Mini SDK version: 4
windowcleaningforums.java
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.windowcleaningforums.co.uk");
mWebView.setWebViewClient(new HelloWebViewClient());
}
}
Main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<webView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.windowcleaningforums"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".windowcleaningforums"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
I am very new and im not quite sure what is causing it any help would be great. Thanks
I get this if that is any help i am not sure what it means though.
[2011-01-12 22:35:07 - DeviceMonitor]Sending jdwp tracking request failed!
This is the log if that helps also i really could do with some help peeps, nobody seems to want to. I know i am new and prob asking stupid questions but how am i supposed to learn if i dont ask questions.
Hi cyberpedz,
Probably just a typo but in your main.xml the WebView tag should have a capital "W" like so:
<WebView xmlns:andro...
You did the right thing looking in the log. That's what helped to figure this one out: there was an exception stack trace in the log. (Keep an eye out for the "AndroidRuntime" tag)
Thanks i have changed that but no difference.
I do have a red dot over a hellowebview class though
When viewing windowcleaningforums.java and looking at the right in outline i have a read dot over hellowebviewclient
Could it be something to do with this bit of code?
Code:
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Try moving the
Code:
//@Override
just before onCreate and uncomment it.
Also Java classes should start with a capital (public class Windowcleaningforum). Make sure you modify the Manifest accordingly.
Ok finally i have it working, it was me being blind i missed a webView now changed to Webview and all works thanks so much.
Now i am trying to get a loading progress bar or even better spinning circle.
What code would i need for this and where abouts in my java bellow would i fit it in?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
/** Called when the activity is first created. */
//@Override
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.WebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.windowcleaningforums.co.uk");
mWebView.setWebViewClient(new HelloWebViewClient());
}
}
Anyone know how to get the spinning circle while pages loads? and how to imput into my code above?
Would be a great help
Ok finally i have a running webview in the market what i would like to do now is add a soft menu for a back, refresh and forward button what code do i need and where would i put it in my java below?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity
{
final Activity activity = this;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
}
So why is it no body wants to help is it the way i ask? is it that developers think they are above the noob? or you really cant b bothered!!
I have even offered to pay for help in the past yet nobody is interested maybe it is that no one really knows the answers.
cyberpedz said:
So why is it no body wants to help is it the way i ask? is it that developers think they are above the noob? or you really cant b bothered!!
I have even offered to pay for help in the past yet nobody is interested maybe it is that no one really knows the answers.
Click to expand...
Click to collapse
It's not that developers can't be bothered, but generally they will have other things to do than help out others. The thing is, you're asking on help for pretty basic stuff. This is something that you should know already, and if don't I suggest you should read through Android's developer website one more time and look at the API examples/demos too.
Hints for your problem; Add the buttons as a merge layout in your XML and then link them with your web view, or add them as menu options. Googling for both will surely give you enough results to get you on your way, these are pretty basic things you want to do after all.

[Q] Choose a string in spinner

Hey guys!
I am working on my first app, cut me some slack for asking please .
So I'm stuck on a little problem:
I have a reader activity and I put a spinner on top of the screen to choose the string where the text comes from:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:id="@+id/kapitelspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/kapitel_prompt" />
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/kapitel1"
/>
</ScrollView>
</LinearLayout>
The TextView in the ScrollView is supposed to be the selected text from the spinner.
Code:
package com.asm.reader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class BookActivity extends Activity {
static final private int CHOOSE_KAPITEL = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_activity);
Spinner spinner = (Spinner) findViewById(R.id.kapitelspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.kapitel_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
}
Code:
package com.asm.reader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
I'm trying to make the spinner choose the string of the textview but i have no idea how to do it. (Already did the toast part)
If anyone could help me it would be greatly appreciated!
Thanks !
bump. the last problem im stuck on
The way I understand what you're trying to do is select an item from the spinner, and set the TextView according to the selected spinner item.
If that is the case you will, for starters, need to set an id attribute for the TextView in the layout xml file.
Then within your onItemSelected() method you need to create a reference to the TextView the same way you did it with the spinner; using the findViewById() method.
Then using that reference you can set the text of the TextView using the same string you got when you created the Toast notification.
Hope that helps!

Text input with DialogFragment

I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a Null pointer exception.
My DialogHost class, this constructs, returns and links the parent to its buttons.
Code:
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
[user=439709]@override[/user]
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
[user=439709]@override[/user]
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
My MainActivity
Code:
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
[user=439709]@override[/user]
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
This is my layout for the add item dialog.
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/hint_add_item" />
</LinearLayout>
It's because in your main activity you are trying to call findViewById:
swapnilraj said:
Code:
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
Click to expand...
Click to collapse
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
SimplicityApks said:
It's because in your main activity you are trying to call findViewById:
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
Click to expand...
Click to collapse
I tried calling findViewById method in the onClick method in the Dialog class, but the function is not defined for a DialogInterface.onClickListner, I modified it to linearl method you told but I cannot get it to work either.
Could you make the changes in the 2 snippets above, it would be very helpful!
You'll have to setup listeners fo this and pass the string or whetever you want to pass to back to the activity which in its turn can handle it (do it by itself or pass this to another fragement).
Although not so much votes (0) the last answer here on stackoverflow has exeactly what you need.

text not showing in listview

I am creating a listview with a custom object containing 1 property(i will be creating other activities using objects with more than 1 property). my problem is it shows the correct number of rows but no text.
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="android link"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView android:id="@+id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
</LinearLayout>
grid_item.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="android link"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="50dp">
<TextView android:id="@+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:text=""
android:layout_alignParentLeft="true"/>
</RelativeLayout>
object java
Code:
package com.example.sarahjmusicprotocol;
import java.io.Console;
public class CategoriesObject
{
String category;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public CategoriesObject()
{
}
public CategoriesObject(String category)
{
this.category=category;
}
private void print()
{
System.out.printf("Category: {0}",category);
}
[user=439709]@override[/user]
public String toString()
{
return this.getCategory();
}
}
adapter java
Code:
package com.example.sarahjmusicprotocol;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CategoryAdapter extends BaseAdapter
{
private List<CategoriesObject> categoryList;
private LayoutInflater layoutInflater;
public CategoryAdapter(final Context context, final List<CategoriesObject> categoriesList)
{
//super(context,0);
this.categoryList = categoriesList;
//this.activity=a;
layoutInflater = LayoutInflater.from(context);
}
public CategoriesObject getItem(int position)
{
return categoryList.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = layoutInflater.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.titleView=(TextView)convertView.findViewById(R.id.item);
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.titleView.setText(categoryList.get(position).getCategory());
return convertView;
}
public int getCount()
{
return categoryList.size();
}
private static class ViewHolder
{
public TextView titleView;
}
}
main java
Code:
package com.example.sarahjmusicprotocol;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends Activity
{
private ListView view;
private CategoryAdapter adapter;
private List<CategoriesObject> categoriesList;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//categoriesList = CategoryDomain.getCategoryDomain().getCategories();
categoriesList = getCategories();
view = (ListView)findViewById(R.id.list);
adapter = new CategoryAdapter(this,categoriesList);
view.setAdapter(adapter);
}
private ArrayList getCategories()
{
ArrayList<CategoriesObject> list = new ArrayList<CategoriesObject>();
list.add(new CategoriesObject("Publishing"));
list.add(new CategoriesObject("Publishing"));
list.add(new CategoriesObject("Publishing"));
list.add(new CategoriesObject("Publishing"));
list.add(new CategoriesObject("Publishing"));
list.add(new CategoriesObject("Publishing"));
return list;
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
any help will be appreciated.
You might want to use a debugger: http://forum.xda-developers.com/showthread.php?t=2325164
nikwen said:
You might want to use a debugger: http://forum.xda-developers.com/showthread.php?t=2325164
Click to expand...
Click to collapse
I'm not getting an error, it just doesn't show the text.
larryse said:
I'm not getting an error, it just doesn't show the text.
Click to expand...
Click to collapse
Yeah, have a look at the posts about using the debuggers of Eclipse or AndroidStudio.
They help you to understand what your app does. You can see which commands get executed at which time and the you can see the values of variables.
That might help you finding the problem.
(This doesn't require an Exception.)

Dealing with Custom ListView and Fragments

Hi guys! Well, i am facing an issue when trying to develop my app. Let me explain what i have done:
1) Create a Login to connect to a MySQL Database to validate the user (Works great)
2) Create a Main activity
3) Create a Drawer, with a Drawer Adapter, to show the options of my dramer menu. (works great)
As you know the drawer works with fragments, so i have one fragment for each menu option.
4) Well, here starts my problem...
The first option on my menu is "Fixture" where i want to show a list of matchs with the differents results. That list, is on a MySql DB.
So, on my fragment (FixtureFragment) i have this code:
Code:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lxp.app.adapter.FixtureAdapter;
import com.lxp.app.model.FixtureItem;
import com.lxp.app.tools.JSONParser;
import com.lxp.app.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FixtureFragment extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// url to get all products list
private static String url_fixture = "http://www.myweb.com/myFixtureData.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIXUTRE = "fixture";
private static final String TAG_EQUIPO1 = "id_equipo_1";
private static final String TAG_EQUIPO2 = "id_equipo_2";
private static final String TAG_GEQUIPO1 = "goles_equipo_1";
private static final String TAG_GEQUIPO2 = "goles_equipo_2";
private static final String TAG_ID_PARTIDO = "id_partido";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray partidos = null;
ArrayList<HashMap<Integer, FixtureItem>> fixtureList;
ListView lv;
public FixtureFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
/**
* Background Async Task to Load the fixture by making HTTP Request
* */
class LoadFixture extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando el Fixture...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting the Fixture from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_fixture, "GET", params);
// Check your log cat for JSON reponse
Log.d("Fixture: ", json.toString());
FixtureItem objFixture = new FixtureItem();
try {
// Checking for SUCCESS TAG
int success = 0;
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
partidos = json.getJSONArray(TAG_FIXUTRE);
// looping through All Products
for (int i = 0; i < partidos.length(); i++) {
JSONObject c = partidos.getJSONObject(i);
Log.e("Json = ", c.toString());
// Storing each json item in variable
String equipo1 = c.getString(TAG_EQUIPO1);
String equipo2 = c.getString(TAG_EQUIPO2);
String golesEq1 = c.getString(TAG_GEQUIPO1);
String golesEq2 = c.getString(TAG_GEQUIPO2);
Integer idPartido = c.getInt(TAG_ID_PARTIDO);
// creating new HashMap
HashMap<Integer, FixtureItem> map = new HashMap<Integer, FixtureItem>();
// adding each child node to HashMap key => value
objFixture.setGolesEquipo1(golesEq1);
objFixture.setGolesEquipo2(golesEq2);
objFixture.setIdequipo1(equipo1);
objFixture.setIdequipo2(equipo2);
objFixture.setIdPartido(idPartido);
map.put(idPartido, objFixture);
fixtureList.add(map);
}
}
} 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
lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
}
}
}
Well, as you could see, i've created a hashmap to load my fixture data, and then i sent this data (fixtureList) to the custom adapter.
When running this code i am getting this error.
Code:
04-05 16:20:27.899 23500-23500/com.lxp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lxp.app, PID: 23500
java.lang.NullPointerException
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:175)
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:632)
Line 175 --> lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
These are the layouts files:
Fragment_Fixture.xml
Code:
<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"
tools:context=".ListActivity" >
<ListView
android:id="@+id/fixture_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fixture_item.xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/idpartido"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:visibility="gone"/>
<TextView
android:id="@+id/golesequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="0"/>
<TextView
android:id="@+id/golesequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="1"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/idequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Argentinos"/>
<TextView
android:id="@+id/idequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Lanus"/>
</LinearLayout>
</LinearLayout>
My fixtureitem class
Code:
public class FixtureItem {
private Integer idPartido;
private String idequipo1;
private String idequipo2;
private String golesEquipo1;
private String golesEquipo2;
public Integer getIdPartido() {
return idPartido;
}
public void setIdPartido(Integer idPartido) {
this.idPartido = idPartido;
}
public String getIdequipo1() {
return idequipo1;
}
public String getIdequipo2() {
return idequipo2;
}
public String getGolesEquipo1() {
return golesEquipo1;
}
public String getGolesEquipo2() {
return golesEquipo2;
}
public void setIdequipo1(String idequipo1) {
this.idequipo1 = idequipo1;
}
public void setIdequipo2(String idequipo2) {
this.idequipo2 = idequipo2;
}
public void setGolesEquipo1(String golesEquipo1) {
this.golesEquipo1 = golesEquipo1;
}
public void setGolesEquipo2(String golesEquipo2) {
this.golesEquipo2 = golesEquipo2;
}
}
and my fixture adapter
Code:
public class FixtureAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
public FixtureAdapter(Context context, ArrayList listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.fixture_item, null);
holder = new ViewHolder();
holder.idequipo1 = (TextView) convertView.findViewById(R.id.idequipo1);
holder.idequipo2 = (TextView) convertView.findViewById(R.id.idequipo2);
holder.golesequipo1 = (TextView) convertView.findViewById(R.id.golesequipo1);
holder.golesequipo2 = (TextView) convertView.findViewById(R.id.golesequipo2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FixtureItem fixtureItem = (FixtureItem) listData.get(position);
holder.idequipo1.setText(fixtureItem.getGolesEquipo1());
holder.idequipo2.setText(fixtureItem.getGolesEquipo2());
holder.golesequipo1.setText(fixtureItem.getGolesEquipo1());
holder.golesequipo2.setText(fixtureItem.getGolesEquipo1());
return convertView;
}
static class ViewHolder {
TextView idequipo1;
TextView idequipo2;
TextView golesequipo1;
TextView golesequipo2;
}
}
I think i am getting wrong because i couldnt find an example of loading data in an asyncronous way for a list inside a fragment, i know is too expecific this example, but i tried differents ways to do it and i couldnt solve it.
If an experienced dev could give me a hand, i will be glad. Or if you have examples of an app working with "Drawer/Fragment/Custom List inside Fragments/Data Loaded from a MySql for the Custom List" it will be great.
If you need more data, just let me know.
Hey i made two apps with remote mysql database . May be i can help .
Sent from my SM-G900T using Tapatalk
Change
Try changing this:
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
// Loading products in Background Thread
new LoadFixture().execute();
return fixtureView;
}
from
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
Same problem
I have the same problem, not able to solve?
Resolved!!
Missed make reference to listView after inflate places:
lv = (ListView) view.findViewById(R.id.fixture_list);
Click to expand...
Click to collapse
Hugs,
Léo
can anybody help me im trying to display the results in the fragment from customlistview adapter ,there is no error at all but its not also displaying the results..

Categories

Resources