Tabs don't display on Kindle Fire - tabs

I have an Android app that uses tabs for its start menu. The tabs don't display when I port the app to a Kindle Fire. Here's the code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:isScrollContainer="true" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/Beginning"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="#+id/Intermediate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="#+id/Advanced"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
</ScrollView>
package com.myproject.project;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
public class TabsTestActivity extends Activity {
/** Called when the activity is first created. */
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_LEVEL = "level";
public static final String KEY_CHART = "charted";
public String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PopulateDatabase();
CopyVideoFiles();
TabHost tabhost = (TabHost) findViewById(R.id.tabhost);
tabhost.setup();
TabSpec spec_beg = tabhost.newTabSpec("Beginning");
spec_beg.setContent(R.id.Beginning);
TextView txtTabInfo = new TextView(this);
txtTabInfo.setText("JUST STARTING");
Typeface font = Typeface.createFromAsset(getAssets(), "danielbd.ttf");
txtTabInfo.setTypeface(font);
txtTabInfo.setGravity(Gravity.CENTER);
txtTabInfo.setHeight(50);
txtTabInfo.setBackgroundColor(Color.parseColor("#CCDE8A"));
txtTabInfo.setTextColor(Color.parseColor("#262405"));
spec_beg.setIndicator(txtTabInfo);
TabSpec spec_int = tabhost.newTabSpec("Intermediate");
spec_int.setContent(R.id.Intermediate);
txtTabInfo = new TextView(this);
txtTabInfo.setText("GETTING THERE");
txtTabInfo.setTypeface(font);
txtTabInfo.setGravity(Gravity.CENTER);
txtTabInfo.setHeight(50);
txtTabInfo.setBackgroundColor(Color.parseColor("#CCDE8A"));
txtTabInfo.setTextColor(Color.parseColor("#262405"));
spec_int.setIndicator(txtTabInfo);
TabSpec spec_adv = tabhost.newTabSpec("Advanced");
spec_adv.setContent(R.id.Advanced);
txtTabInfo = new TextView(this);
txtTabInfo.setText("REALLY GOOD");
txtTabInfo.setTypeface(font);
txtTabInfo.setGravity(Gravity.CENTER);
txtTabInfo.setHeight(50);
txtTabInfo.setBackgroundColor(Color.parseColor("#CCDE8A"));
txtTabInfo.setTextColor(Color.parseColor("#262405"));
spec_adv.setIndicator(txtTabInfo);
// get data from database, create buttons and name them
SQLData myTable = new SQLData(this);
myTable.open();
Cursor c = myTable.getallData();
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iLevel = c.getColumnIndex(KEY_LEVEL);
// create the buttons
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
final String RowNum = c.getString(iRow);
String Name = c.getString(iName);
final String Level = c.getString(iLevel);
Button button = new Button(this);
button.setText(Name);
button.setHeight(20);
button.setTextColor(Color.BLACK);
button.setBackgroundColor(Color.parseColor("#A89E0A"));
button.setHighlightColor(Color.WHITE);
button.setTypeface(font);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent choice = new Intent(getApplicationContext
(),
com.myproject.project.myclass.class);
Bundle dataBundle = new Bundle();
dataBundle.putString("RowID", RowNum);
dataBundle.putString("Level", Level);
choice.putExtras(dataBundle);
try {
startActivity(choice);
} catch (Exception e) {
Dialog d = new Dialog(getApplicationContext());
d.setTitle("TabsTestActivity line 131");
TextView tv = new TextView(getApplicationContext());
tv.setText(e.toString());
d.setContentView(tv);
d.show();
} finally {
}
}
});
LinearLayout lbeg = (LinearLayout) findViewById(R.id.Beginning);
LinearLayout lint = (LinearLayout) findViewById(R.id.Intermediate);
LinearLayout ladv = (LinearLayout) findViewById(R.id.Advanced);
if (Level.equals("Beginning"))
lbeg.addView(button);
else if (Level.equals("Intermediate"))
lint.addView(button);
else if (Level.equals("Advanced"))
ladv.addView(button);
}
tabhost.addTab(spec_beg);
tabhost.addTab(spec_int);
tabhost.addTab(spec_adv);
myTable.close();
}}
Does anyone know why? The tabs and their contents show up fine in the emulator and on my Android phone. Thanks!

I have since learned that the Kindle Fire does not support Tabs

Related

call permission which may be rejected for setMyLocationEnable android

Alas! after a lots of efforts and search I couldn't find my problem. I want to find current location in google map but I am still getting an error(required permissions).
call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with check
permission) or explicitly handle a potential 'security Exception'
at gMap.setMyLocationEnable(true); Please anybody guide me how can I fix it? My code is given below.
AddMasjid.java
package com.example.saroosh.masjidnow.Tabs;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.saroosh.masjidnow.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class AddMasjid extends Fragment implements OnMapReadyCallback{
MapView gMapView;
GoogleMap gMap = null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.add_masjid,container,false);
gMapView = (MapView) v.findViewById(R.id.map);
gMapView.getMapAsync(this);
gMapView.onCreate(savedInstanceState);
gMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
gMap.setMyLocationEnabled();
}
}
#Override
public void onResume() {
super.onResume();
gMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
gMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
gMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
gMapView.onLowMemory();
}
}
add_masjid.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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentStart="true"
android:text="#string/xyz"
android:textColor="#FFFFFF"
android:textSize="20sp"
/>
<Button
android:id="#+id/generalId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:background="#drawable/rect1"
android:onClick="geoLocate"
android:text="#string/abc"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/textView1"
android:layout_toStartOf="#+id/generalId"
android:ems="10"
android:inputType="text"
android:background="#FFFFFF"
android:labelFor="#+id/editText1"
android:layout_above="#+id/map"
android:layout_alignParentTop="true" />
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/generalId">
</com.google.android.gms.maps.MapView>
</RelativeLayout>
I have just solved my problem by adding some permissions in it.
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
//add this code...
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}

App crashes everytime run with error "Unfortunately MyApplication1 has stopped"

I am using Volley library for fetching the json data. I have also modified the Manifest adding the necessary Internet permission . But when I run the app it crashes.
Main activity.java
package com.example.sans.myapplication1;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
listView=(ListView)findViewById(R.id.list);
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, "http://api.themoviedb.org/3/movie/popular?api_key=fa468af9e769ba5fbc027e9e933130ed",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Movie> movieList= new ArrayList<Movie>();
try{
JSONArray jsonArray=response.getJSONArray("results");
for (int i=0;i< jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String title= jsonObject.getString("title");
movieList.add(new Movie(title));
MovieAdapter adapter= new MovieAdapter(getApplicationContext(),movieList);
listView.setAdapter(adapter);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error getting data", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
$ MovieAdapter.java
package com.example.sans.myapplication1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by sans on 13/7/16.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(Context context, List<Movie> objects) {
super(context,0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie=getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.list_row, parent);
}
TextView title=(TextView)convertView.findViewById(R.id.title);
title.setText(movie.getTitle());
return convertView;
}
}
$ Movie.java
package com.example.sans.myapplication1;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by sans on 13/7/16.
*/
public class Movie {
private String title;
public Movie(String title){
this.title=title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
$ list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/listPreferredItemHeight"
android:id="#+id/title"/>
</LinearLayout>
$ content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sans.myapplication1.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</RelativeLayout>
Log error
FATAL EXCEPTION: main
Process: com.example.sans.myapplication1, PID: 4252
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sans.myapplication1.MovieAdapter.getView(MovieAdapter.java:29)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
at android.widget.ListView.onMeasure(ListView.java:1188)
at android.view.View.measure(View.java:18788)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18788)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 17:37:39.746 1532-1903/? W/ActivityManager: Force finishing activity com.example.sans.myapplication1/.MainActivity
In MovieAdapter.java class change convertView!=null to convertView==null
& in list_row.xml file
instead of android:minHeight="?attr/listPreferredItemHeight"
change it to android:minHeight="?android:attr/listPreferredItemHeight"

Material design fixed tabs without toolbar

I have a slight problem figuring out a "bug" in my code. Im not sure if its a bug or not. However, as you can see in the picture 1, the fixed tabs' position is behind the curtain drawer. I cant find/understand why this is. Ive followed several tutorials and they dont seem to have the same problem.
Ive tried to google it up, but i cant find a similar problem. Anyone experienced something similar before?
In the android studio, the design layout seems to be on point, however, not when compiled.
Im using the neokree lib so i can use the icons and ripple effect when selecting tabs. I've tried to use the google's tab layout link here, but as soon as i tried to remove the actionbar and apply the icons, the same problem occurred.
Thanks!
activity_main
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<it.neokree.materialtabs.MaterialTabHost
android:id="#+id/materialTabHost"
android:layout_width="match_parent"
android:layout_height="48dp"
app:iconColor="#color/iconColor"
app:primaryColor="#color/primaryColor"
app:accentColor="#color/accentColor"
app:hasIcons="true"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
styles.xml
<resources>
<style name="AppTheme" parent="AppTheme.Base"></style>
<style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="colorAccent">#color/accentColor</item>
<item name="colorControlHighlight">#color/colorHighlight</item>
</style>
</resources>
styles.xml v21
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<!--Using same style as in default style.xml file-->
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:colorPrimary">#color/primaryColor</item>
<item name="android:colorPrimaryDark">#color/primaryColorDark</item>
<item name="android:colorAccent">#color/accentColor</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:colorControlHighlight">#color/colorHighlight</item>
</style>
</resources>
MainActivity
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
public class MainActivity extends ActionBarActivity implements MaterialTabListener
{
private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
private MaterialTabHost tabHost;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
viewPager = (ViewPager) findViewById(R.id.viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
tabHost.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < adapter.getCount(); i++) {
tabHost.addTab(
tabHost.newTab()
.setIcon(adapter.getIcon(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(MaterialTab materialTab) {
viewPager.setCurrentItem(materialTab.getPosition());
}
#Override
public void onTabReselected(MaterialTab materialTab) {
}
#Override
public void onTabUnselected(MaterialTab materialTab) {
}
class ViewPagerAdapter extends FragmentStatePagerAdapter
{
int icons[] = {R.drawable.ic_home,
R.drawable.ic_graph,
R.drawable.ic_bell_mid,
R.drawable.ic_settings};
//String[] tabText = getResources().getStringArray(R.array.tabs);
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
//tabText = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position)
{
MyFragment myFragment = MyFragment.getInstance(position);
return myFragment;
}
//Attaching an image to a (spannable) string so we can show the image instead of text.
#Override
public CharSequence getPageTitle(int position){
/*Drawable drawable = getResources().getDrawable(icons[position]);
//icon bounds/size
drawable.setBounds(0,0,96,96);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;*/
return getResources().getStringArray(R.array.tabs)[position];
}
#Override
public int getCount()
{
return 4;
}
private Drawable getIcon(int position)
{
return getResources().getDrawable(icons[position]);
}
}
}
After accidentally getting over a youtube tutorial about making simple material design tabs, I made a new project and started to combine the one I found in youtube with my old one. Eventually, I found out that the following code line in the styles file was the cause of the problem.
<item name="android:windowTranslucentStatus">true</item>
It seems like it was something I added for testing and forgot to remove later on.
Try adding a Toolbar with a no actionbar theme..
In order to do this you have to make a new xml file called tool_bar.xml and paste the following code into it:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/ColorPrimary"
android:elevation="2dp"
android:theme="#style/Theme.AppCompat.NoActionBar"
xmlns:android="http://schemas.android.com/apk/res/android" />
You have then add this to your activity_main.xml file:
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>

I need to open a local html for each item in listview, how do? Android

I have a listview with onclick, but I need each item clicked open a html in assets folder, I have some html .. then need to open each item one.
You can use below code to open local html file from your app assets folder
Intent intent=new Intent(this, WebviewActivity.class);
intent.putExtra("url","file:///android_asset/local.html");
startActivity(intent);
WebviewActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
public class WebviewActivity extends Activity {
private WebView mWebView;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mWebView = (WebView) findViewById(R.id.webview);
Intent intent=getIntent();
url=intent.getStringExtra("url");
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
}
}
activity_webview.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webviewRootContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webview"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

Dynamically updating a ListView from JSON object using a custom ListViewAdapter

As usual the question comes from a first time user of Android. Its three weeks later and im tearing my hair out will do my best to explain the problem.
Firstly I am using Exlipse 3.7.1 and SDK r15 as of today because I thought Ill try upgrade maybe thats whats causing the issues but seems to be the same while using r13.
Here is a working copy of my code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"
android:id="#+id/llMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:background="#drawable/header"
android:id="#+id/linearLayout1"
android:layout_height="50dp"
android:layout_width="fill_parent">
<ImageButton
android:background="#null"
android:id="#+id/ibHome"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight=".25"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/trophy_cup" />
<ImageView
android:background="#000000"
android:id="#+id/imageView1"
android:layout_height="match_parent"
android:layout_width="1dp" />
<TextView
android:gravity="center_horizontal"
android:id="#+id/lblHome"
android:layout_height="50dp"
android:layout_width="0dp"
android:layout_weight="1"
android:paddingTop="14dp"
android:text="#string/helloHome"
android:textColor="#color/txtYellow"
android:textSize="18dp"
android:textStyle="bold"
android:typeface="serif" />
<ImageView
android:id="#+id/imageView2"
android:layout_height="match_parent" android:background="#000000"
android:layout_width="1dp" />
<ImageButton
android:background="#null"
android:focusable="true"
android:id="#+id/ibQuit"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight=".25"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/yellow_flag" />
</LinearLayout>
<!-- Body code goes here -->
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="1"
android:gravity="center_horizontal" android:paddingTop="10dp">
<TextView
android:id="#+id/lblHeading"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_weight="0.17"
android:gravity="center_horizontal"
android:isScrollContainer="true"
android:text="Top"
android:textColor="#color/txtYellow"
android:textSize="22dp"
android:textStyle="bold" android:paddingTop="7dp" android:typeface="serif"/>
<Spinner
android:entries="#array/strArrTop"
android:id="#+id/spinTop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_weight="0.44"
android:focusableInTouchMode="true"
android:longClickable="true"/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center_horizontal"
android:padding="25dp"
android:orientation="vertical" >
<ListView
android:id="#+id/list1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:isScrollContainer="true" />
</LinearLayout>
<!-- End Body code goes here -->
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" >
<TextView
android:id="#+id/lblWidth"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
<ImageView
android:layout_height="120dp"
android:layout_width="201dp"
android:scaleType="fitXY"
android:src="#drawable/ddo_logo" />
<TextView
android:id="#+id/lblHeight"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
</LinearLayout>
mylist.xml (the custom list adapter)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content" android:gravity="left|center">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:layout_weight="0.21"
android:textColor="#color/txtYellow" />
<TextView
android:id="#+id/txt2"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:textColor="#color/txtYellow" />
</LinearLayout>
</LinearLayout>
The manifest file, uses minSDK 8.0
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hunta.DDOFastestTimes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<supports-screens
android:normalScreens="true"
android:largeScreens="true" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".DDOFastestTimesActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and finally the offending java file:
package com.hunta.DDOFastestTimes;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.ParseException;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class DDOFastestTimesActivity extends Activity implements OnClickListener {
/** JSON variables */
String jc1, jc2 = null;
/** END JSON variables */
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** JSON variables */
String result = null;
InputStream is = null;
StringBuilder sb = null;
/** END JSON variables */
ImageButton closeApp = (ImageButton) findViewById(R.id.ibQuit);
closeApp.setOnClickListener(this);
/** http://www.dcpagesapps.com/developer-resources/android/21-android-tutorial-spinners?start=1 */
/** Populating the spinner from that string-array */
Spinner s = (Spinner) findViewById( R.id.spinTop );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.strArrTop, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
/** END Populating the spinner from that string-array */
/** Create a reference to our spinner */
s.setAdapter( adapter );
/** END Create a reference to our spinner */
/** END http://www.dcpagesapps.com/developer-resources/android/21-android-tutorial-spinners?start=1 */
s.setOnItemSelectedListener(new MyOnItemSelectedListener());
/** JSON code to initiate the php */
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url-to-my-php-file/fastag.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
JSONArray jArray;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
// Adding the JSON data to the list view
int length = jArray.length();
List<String> listContents1 = new ArrayList<String>(length);
List<String> listContents2 = new ArrayList<String>(length);
// Convert ListString Array to an ArrayList
ArrayList<tblRecord> arrTxt = new ArrayList<tblRecord>();
// Changing the ListViews
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
jc1 = json_data.getString("c1");
jc2 = json_data.getString("c2");
listContents1.add(json_data.getString("c1"));
listContents2.add(json_data.getString("c2"));
// Create an Array to pass to our custom view
tblRecord addRecord = new tblRecord(jc1, jc2);
arrTxt.add(addRecord);
}
ListView myListView1 = (ListView) findViewById(R.id.list1);
myListView1.setAdapter(new UserItemAdapter(this, android.R.layout.simple_list_item_1, arrTxt));
// END Adding the JSON data to the list view
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Results Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
/** END JSON code to initiate the php */
}
/** End Called when the activity is first created. */
/** Using a custom List View */
public class UserItemAdapter extends ArrayAdapter<tblRecord> {
private ArrayList<tblRecord> arrList;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<tblRecord> arrList) {
super(context, textViewResourceId, arrList);
this.arrList = arrList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mylist, null);
}
tblRecord user = arrList.get(position);
if (user != null) {
TextView c1 = (TextView) v.findViewById(R.id.txt1);
TextView c2 = (TextView) v.findViewById(R.id.txt2);
if (c1 != null) {
c1.setText(user.c1);
}
if(c2 != null) {
c2.setText(user.c2);
}
}
return v;
}
}
public class tblRecord {
public String c1;
public String c2;
public tblRecord(String c1, String c2) {
this.c1 = c1;
this.c2 = c2;
}
}
/** END Using a custom List View */
/** Listener for the spinner, we will handle changes made to the spinner here */
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(parent.getContext(), "The top " +
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
/** END Listener for the spinner, we will handle changes made to the spinner here */
#Override
public void onClick(View v) {
int id = v.getId();
// Intent myIntent;
switch (id) {
case R.id.ibQuit:
finish();
break;
}
}
}
Up until this point everything is working, if not 100% at least it works but now I need to try dynamically change the contents of the list view when the user changes the spinner.
The emulator uses -dns-server xxx.xxx.xxx.xxx in its run configuration
I am running 3.7in WVGA
Now after an 8 hour attempt to find a way to do this, this is as far as I have gotten but it just crashes:
package com.hunta.DDOFastestTimes;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.net.ParseException;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class DDOFastestTimesActivity extends ListActivity implements OnClickListener {
private UserItemAdapter myAdapter;
private ArrayList<tblRecord> arrTxt = null;
private Runnable viewJSON;
/** JSON variables */
String jc1, jc2, result = null;
InputStream is = null;
StringBuilder sb = null;
/** END JSON variables */
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton closeApp = (ImageButton) findViewById(R.id.ibQuit);
closeApp.setOnClickListener(this);
/** http://www.dcpagesapps.com/developer-resources/android/21-android-tutorial-spinners?start=1 */
/** Populating the spinner from that string-array */
Spinner s = (Spinner) findViewById( R.id.spinTop );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.strArrTop, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
/** END Populating the spinner from that string-array */
/** Create a reference to our spinner */
s.setAdapter( adapter );
/** END Create a reference to our spinner */
/** END http://www.dcpagesapps.com/developer-resources/android/21-android-tutorial-spinners?start=1 */
s.setOnItemSelectedListener(new MyOnItemSelectedListener());
arrTxt = new ArrayList<tblRecord>();
this.myAdapter = new UserItemAdapter(this, R.layout.mylist, arrTxt);
setListAdapter(this.myAdapter);
viewJSON = new Runnable(){
#Override
public void run() {
arrTxt = MyJSONFetch(0);
}
};
Thread thread = new Thread(null, viewJSON, "MagentoBackground");
thread.start();
ListView myListView1 = (ListView) findViewById(R.id.list1);
myListView1.setAdapter(new UserItemAdapter(this, android.R.layout.simple_list_item_1, arrTxt));
}
/** End Called when the activity is first created. */
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(arrTxt != null && arrTxt.size() > 0){
myAdapter.notifyDataSetChanged();
for(int i=0;i<arrTxt.size();i++)
myAdapter.add(arrTxt.get(i));
}
myAdapter.notifyDataSetChanged();
}
};
/** Using a custom List View */
public class UserItemAdapter extends ArrayAdapter<tblRecord> {
private ArrayList<tblRecord> arrTxt;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<tblRecord> arrTxt) {
super(context, textViewResourceId, arrTxt);
this.arrTxt = arrTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mylist, null);
}
tblRecord user = arrTxt.get(position);
if (user != null) {
TextView c1 = (TextView) v.findViewById(R.id.txt1);
TextView c2 = (TextView) v.findViewById(R.id.txt2);
if (c1 != null) {
c1.setText(user.c1);
}
if(c2 != null) {
c2.setText(user.c2);
}
}
return v;
}
}
public class tblRecord {
public String c1;
public String c2;
public tblRecord(String c1, String c2) {
this.c1 = c1;
this.c2 = c2;
}
}
/** END Using a custom List View */
/** Reload JSON Database from onclick listener */
public ArrayList<tblRecord> MyJSONFetch(int position)
{
ArrayList<tblRecord> arrTxt = new ArrayList<tblRecord>();
String tmpUrl = null;
/** JSON code to initiate the php */
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
switch (position)
{
case 0:
tmpUrl = "http://smutlow.comp-degree.uhi.ac.uk/UG409713/DDOFastestTimes/fastag.php";
break;
case 1:
tmpUrl = "http://smutlow.comp-degree.uhi.ac.uk/UG409713/DDOFastestTimes/fastas.php";
break;
}
HttpPost httppost = new HttpPost(tmpUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
JSONArray jArray;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
// Adding the JSON data to the list view
int length = jArray.length();
List<String> listContents1 = new ArrayList<String>(length);
List<String> listContents2 = new ArrayList<String>(length);
// Changing the ListViews
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
jc1 = json_data.getString("c1");
jc2 = json_data.getString("c2");
listContents1.add(json_data.getString("c1"));
listContents2.add(json_data.getString("c2"));
// Create an Array to pass to our custom view
tblRecord addRecord = new tblRecord(jc1, jc2);
arrTxt.add(addRecord);
}
// END Adding the JSON data to the list view
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Results Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
/** END Reload JSON Database from onclick listener */
runOnUiThread(returnRes);
return arrTxt;
}
/** Listener for the spinner, we will handle changes made to the spinner here */
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
MyJSONFetch(position);
Toast.makeText(parent.getContext(), "The top " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
MyJSONFetch(position);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
/** END Listener for the spinner, we will handle changes made to the spinner here */
#Override
public void onClick(View v) {
int id = v.getId();
// Intent myIntent;
switch (id) {
case R.id.ibQuit:
finish();
break;
}
}
}
Basically Ive tried to seperate the JSON code from the onCreate and put it into its own public method so I can call it from the MyOnItemSelectedListener but I am out of ideas and have demonstrated my total lack of understanding of java.
Please if you respond try be a simplistic as possible with your answer.
Thank you in advance.
p.s. apologies if the layout isn't what it should be this is my first post
So I have found a solution to this perhaps someone might offer a better one but here is what I did:
Rather than try to fire the PHP I needed from the spinner I opted to use the spinner to load a new Intent with the relevant URL to the PHP I wanted to use added to a Bundle.
if (position == 0) {
Bundle myBundle = new Bundle();
Intent myIntent;
myBundle.putString("myPHP", "http://url-to-my-php-file/fastag.php");
myIntent = new Intent(getBaseContext(), DDOFastestGuilds.class);
myIntent.putExtras(myBundle);
startActivity(myIntent);
onLowMemory();
finish();
}
I then added two new .java files practically identical to the first one, adding two lines at the start:
Bundle myBundle = getIntent().getExtras();
String tmpPHP = myBundle.getString("myPHP");
I amended the line that calls the HttpPost to point to the variable I just created tmpPHP rather than the literal URL I had used in the original file:
HttpPost httppost = new HttpPost(tmpPHP);
And lastly changing the spinners selection to reflect that last selected by the user, if there were more than two options in the spinner I would have used the bundle to pass the last selected index but in my example I only had two options so I knew the selected index was either 0 or 1 depending on the Intent i wanted to open. (Making sure its directly after the setAdapter method):
s.setSelection(1);
Hoping for an alternative method going forward.
If anyone can suggest a way to only have to use one Activity to get the same result I would be grateful.