Hello i've build already smartphone apps but now i'm starting working on a project to make my app compatible with tablets. Now i'm using fragments this is my first using fragments so thats why i need your advice, please help or give me examples with my code. Many thanks already
my code my "news" class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Nieuws extends FragmentActivity{
// Connection detector
//ConnectionDetector cd;
// Alert dialog manager
//AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
//private ProgressDialog pDialog;
private static String URL = "http://localhost/fetch.php?page=2&android";
// JSON Node namen
static final String TAG_DATA = "data";
static final String TAG_ID = "id";
static final String TAG_CATEGORY = "category";
static final String TAG_TITLE = "title";
static final String TAG_AUTHOR = "author";
static final String TAG_DATE = "date";
static final String TAG_INTRODUCTION = "introduction";
static final String TAG_CONTENT = "content";
static final String TAG_THUMBNAIL = "thumbnail";
static final String TAG_MEDIA = "media";
static final String TAG_SOURCE = "source";
static final String TAG_LINKEDMEDIA = "linkedMedia"; //array waarin de plaatjes zitten*/
// Nieuws JSONArray
JSONArray newsArray;
ListView list;
LazyAdapter adapter;
private PullToRefreshListView mPullRefreshListView;
ArrayList<HashMap<String, String>> newsList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nieuws);
//list=(ListView)findViewById(R.id.list);
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
/* FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
StartFragment myFragment = new StartFragment();
ft.add(R.id.myFragment, myFragment);
ft.commit();*/
/* cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Nieuws.this, "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
// stop executing code by return
return;
}*/
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetJSONData().execute();
}
});
//Async
new GetJSONData().execute();
}
class GetJSONData extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>{
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
//pDialog = new ProgressDialog(Nieuws.this);
//pDialog.setMessage("Nieuws laden ...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
}
/**
* Get de json
*/
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
// Hashmap voor listView
final ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Maak een JSON Parser instance
JSONParser jParser = new JSONParser();
// Pakt JSON string uit URL
JSONObject json = jParser.getJSONFromUrl(URL);
try{
// Pakt de Array van Nieuwsartikelen
newsArray = json.getJSONArray(TAG_DATA);
// Loop door alle Nieuwsartikels
for(int i=0; i < newsArray.length(); i++){
JSONObject c = newsArray.getJSONObject(i);
// Het plaatsen van elk json item in variabele
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
//String introduction = c.getString(TAG_INTRODUCTION);
String thumbnail = c.getString(TAG_THUMBNAIL);
String linkedMedia = c.getString(TAG_LINKEDMEDIA);
//String thumbnailName = c.getString(TAG_THUMBNAIL);
//String thumbnailFormat = "http://iappministrator.com/mooiwark/media/%s";
//String thumbnail = String.format(thumbnailFormat, thumbnailName);
// maak een nieuwe HashMap
HashMap<String, String> map = new HashMap<String, String>();
// voeg elk item child node in de Hashmap -> value
map.put(TAG_TITLE, title);
map.put(TAG_CONTENT, content);
map.put(TAG_DATE, date);
//map.put(TAG_INTRODUCTION, introduction);
map.put(TAG_THUMBNAIL, thumbnail);
map.put(TAG_LINKEDMEDIA, linkedMedia);
// voeg de HashList toe aan ArrayList
newsList.add(map);
// Click event for single list row
mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
//list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = newsList.get(position - 1);
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//Intent in = new Intent(SingleMenuItemActivity.this, org.scout.android.library.LibraryDetail.class);
in.putExtra(TAG_TITLE, map.get(TAG_TITLE));
in.putExtra(TAG_CONTENT, map.get(TAG_CONTENT));
in.putExtra(TAG_DATE, map.get(TAG_DATE));
//in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
in.putExtra(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
in.putExtra(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));
startActivity(in);
}
});
}
} catch(JSONException e){
e.printStackTrace();
}
return newsList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
//De items worden ingeladen
adapter=new LazyAdapter(Nieuws.this, result, R.layout.list_row,
new String[]{TAG_TITLE, TAG_CONTENT, TAG_DATE, TAG_THUMBNAIL}, new int[] {
R.id.title, R.id.subtitle, R.id.date, R.id.list_image}); //TAG_INTRODUCTION mist nog
//list.setAdapter(adapter);
mPullRefreshListView.setAdapter(adapter);
// dismiss the dialog after getting all deelnemers
//pDialog.dismiss();
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
}
in this activity it would normally load the content when on click. this class is the one which i've tried to turn into a fragments class
"SingleMenuItemActivity" class :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleMenuItemActivity extends Fragment {
// JSON node keys
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
private static final String TAG_DATE = "date";
private static final String TAG_LINKEDMEDIA = "linkedMedia";
//private static final String TAG_THUMBNAIL = "thumbnail";
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
/*#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);*/
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.single_list_item, container, false);
return view;
cd = new ConnectionDetector(getActivity().getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(), "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
// stop executing code by return
return;
}
// getting intent data
Intent in = getIntent().getExtras();
//final String image_url = in.getStringExtra(TAG_THUMBNAIL);
final String image_url = in.getStringExtra(TAG_LINKEDMEDIA);
ImageView imgv = (ImageView) getView().findViewById(R.id.images_label);
ImageLoader imageLoader = new ImageLoader(getActivity().getApplicationContext());
imageLoader.DisplayImage(image_url, imgv);
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String date = in.getStringExtra(TAG_DATE);
String message = in.getStringExtra(TAG_CONTENT);
//String images = in.getStringExtra(TAG_IMAGES);
//Bitmap bitmap = in.getParcelableExtra(TAG_IMAGES);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);
// Displaying all values on the screen
TextView lblTitle = (TextView)getView().findViewById(R.id.title_label);
TextView lblDate = (TextView) getView().findViewById(R.id.date_label);
TextView lblMessage = (TextView) getView().findViewById(R.id.message_label);
//ImageView lblImages = (ImageView) findViewById(R.id.images_label);
//TextView lblImages = (TextView) findViewbyId(R.id.images_label);
// loader image
//int loader = R.drawable.loader;
System.out.println("Ja en nu werkt het niet meer");
// image url
//String image_url = "http://d24w6bsrhbeh9d.cloudfront.net/photo/5614379_460s.jpg";
//ImageLoader imgLoader = new ImageLoader(getApplicationContext());
//-imgLoader.DisplayImage(song.get(CustomizedListView.TAG_IMAGES), lblImages);
System.out.println("Error? haha bam jammer dan:");
//imgLoader.DisplayImage(images, lblImages);
//System.out.println("Plaatjes?:"+ images);
lblTitle.setText(title);
lblDate.setText(date);
lblMessage.setText(message);
//lblImages.setImageURI(Uri.parse(images));
//ImageLoader imageLoader = new ImageLoader(getApplicationContext());
//imageLoader.DisplayImage(images,lblImages);
//lblImages.setImageResource(images);
//imageLoader.displayImage(images);
//lblImages.setImageBitmap(bitmap);
//lblImages.setImageResource(R.drawable.bitmap);
//lblImages.setImageResource(images);
/*if (d instanceof BitmapDrawable) {
Bitmap bm = ((BitmapDrawable)d).getBitmap();
//Maybe more code here?
lblImages.setImageBitmap(bm);
}*/
//lblImages.setImageResource(images);
//lblImages.DisplayImage(images);
//lblImages.DisplayImage(images);
}
}
Now i'm getting to the part which i don't understand my Intent in = getIntent() doesn't work i get errors. Can someone guide me on turning from code form a activity to a fragment many thanks already
Screenshot:
Left the "news class" right "SingleMenuItemActivity"
It's going wrong when i click the onclick in the class on the left.
First of all i advise you to use a ListFragment for your list and define a listerner for onclick event (this listener could be your Nieuws activity).
Then you will need to have 2 layouts. The classic one with one fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/onepane_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
</LinearLayout>
and the other one with two fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/towpane_layout">
<fragment android:id="#+id/listFragment"
android:layout_height="fill_parent"
android:name="com.example.MyListFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="#+id/displayFragment"
android:layout_height="fill_parent"
android:name="com.example.MyDisplayFragment"
android:layout_width="fill_parent" />
</LinearLayout>
in your Nieuws Activity you will check if the layout loaded has two fragments if not you will load the ListFragment using the fragment manager
//Check that the activity is not using the layout with fragment;
if(findViewById(R.id.onepane_layout) != null) {
if (savedInstanceState != null) {
return;
}
MyListFragment lFragment = new MyListFragment ();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
lFragment .setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction()
.add(R.id.onepane_layout, lFragment ).commit();
}
Then in your on item selection method you need again to load the display fragment if you are in one pane mode:
MyDisplayFragment dispFrag = (MyDisplayFragment)
getSupportFragmentManager().findFragmentById(R.id.displayFragment);
if (dispFrag != null) {
// If display frag is available, we're in two-pane layout...
// Call a method in the DisplayFragment to update its content
dispFrag.updateView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
MyDisplayFragment newFragment = new MyDisplayFragment ();
Bundle args = new Bundle();
args.putInt(MyDisplayFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
There is more to explain but this is the basics. You may need to check these two usefull links:
http://developer.android.com/training/multiscreen/adaptui.html
http://developer.android.com/training/basics/fragments/fragment-ui.html
You will need also to handle screen rotation.
In your FragmentActvity, instead of creating Intent, you need to create object of Bundle
mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
//list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = newsList.get(position - 1);
Bundle in = new Bundle();
in.putString("TAG_TITLE",map.get(TAG_TITLE));
in.putString(TAG_TITLE, map.get(TAG_TITLE));
in.putString(TAG_CONTENT, map.get(TAG_CONTENT));
in.putString(TAG_DATE, map.get(TAG_DATE));
//in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
in.putString(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
in.putString(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));
SingleMenuItemActivity singleMenu = new SingleMenuItemActivity(in);
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(android.R.id.content, SingleMenuItemActivity);
fragmentTransaction.addToBackStack("");//if needed
fragmentTransaction.commit();
}
});
}
In your SingleMenuItemActivity class create constructor, which accept the parameter a Bundle object
public DetailActvity(Bundle bundle)
{
this.bundle=bundle;//update global Bundle object
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mView= inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container,false);
imgView = (ImageView)mView.findViewById(R.id.imageView1);
tvDetail = (TextView)mView.findViewById(R.id.tvDetail);
String detail=bundle.getString("KEY");
tvDetail.setText(detail);
String image=bundle.getString("KEY");
return mView;
}
Related
I am very new to android development and I was following Stanford CS193A lectures to learn something. While trying to create dictionary(without using stand-ford library), i feel like I did most of the things right but I am not able to launch app on phone. Here my java code. Please help me.
package com.hfad.dictionarytwo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
private HashMap<String, String> dictionary;
private ArrayList<String> list;
private ArrayAdapter<String> adapter;
private ArrayList<String> fiveDefns;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dictionary = new HashMap<String,String>();
list = new ArrayList<String>();
fiveDefns = new ArrayList<String>();
readWordsFromFile();
pickRandomWords();
}
private void readWordsFromFile(){
Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
//following delimator is for spliting at tab
while (scan.hasNextLine()){
String line = scan.nextLine();
String[] parts = line.split("\t");
if (parts.length >= 2){
String word = parts[0];
String defn = parts[1];
list.add(word);
dictionary.put(word,defn);
}
}
}
private void pickRandomWords() {
//folowing code shuffles all the words and takes the first three words
ArrayList<String> threeWords = new ArrayList<String>();
Collections.shuffle(list);
for (int i = 0; i < 5; i++) {
threeWords.add(list.get(i));
}
//display the first word, after shuffling ofcourse
final String theWord = threeWords.get(0);
TextView theWordView = findViewById(R.id.the_word);
theWordView.setText(theWord);
fiveDefns.clear();
for (String word : threeWords) {
fiveDefns.add(dictionary.get(word));
}
//shuffle it again
Collections.shuffle(fiveDefns);
//make adapter to show three definitions on screen
if (adapter == null) {
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, fiveDefns);
} else {
adapter.notifyDataSetChanged();
}
ListView listView = findViewById(R.id.word_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the posiiton of definition user clicked from threeDefn arraylist
String defnClicked = (String) fiveDefns.get(position);
//want to know if it is right definition
String rightAnswer = dictionary.get(theWord);
if (defnClicked.equals(rightAnswer)) {
//note that just 'this' will not work b/c we want to refer to over all activity
//not this little activity, which is small activity inside overall activity
Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
}
pickRandomWords();
}
});
}
}
I have grewords txt file in my res directory .
In your activity change condition in readWordsFromFile() and call pickRandomWords() from readWordsFromFile().
See the below code.
Make sure that your file has content like :
abcd kolkata valsad
123 auto vapi
789 neha palghar
klj ma ghfgh
mnk fgdgdf papa
Note: In your text file data should be in the above format.because you split words using space("\t").
public class MainActivity extends AppCompatActivity {
private HashMap<String, String> dictionary;
private ArrayList<String> list;
private ArrayAdapter<String> adapter;
private ArrayList<String> fiveDefns;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dictionary = new HashMap<String,String>();
list = new ArrayList<String>();
fiveDefns = new ArrayList<String>();
readWordsFromFile();
}
private void readWordsFromFile(){
Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
//following delimator is for spliting at tab
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.contains(" ")) {
String[] parts = line.split(" ");
if (parts.length >= 1) {
String word = parts[0];
String defn = parts[1];
list.add(word);
dictionary.put(word, defn);
}
}
}
pickRandomWords();
}
private void pickRandomWords() {
//folowing code shuffles all the words and takes the first three words
ArrayList<String> threeWords = new ArrayList<String>();
Collections.shuffle(list);
for (int i = 0; i < 3; i++) {
threeWords.add(list.get(i));
}
//display the first word, after shuffling ofcourse
final String theWord = threeWords.get(0);
TextView theWordView = findViewById(R.id.the_word);
theWordView.setText(theWord);
fiveDefns.clear();
for (String word : threeWords) {
fiveDefns.add(dictionary.get(word));
}
//shuffle it again
Collections.shuffle(fiveDefns);
//make adapter to show three definitions on screen
if (adapter == null) {
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, fiveDefns);
} else {
adapter.notifyDataSetChanged();
}
ListView listView = findViewById(R.id.word_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the posiiton of definition user clicked from threeDefn arraylist
String defnClicked = (String) fiveDefns.get(position);
//want to know if it is right definition
String rightAnswer = dictionary.get(theWord);
if (defnClicked.equals(rightAnswer)) {
//note that just 'this' will not work b/c we want to refer to over all activity
//not this little activity, which is small activity inside overall activity
Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
}
pickRandomWords();
}
});
}
}
** Note:** you just replace the above code in your file.
I have a ListView in a ListFragment and in the code I wrote a code that says when an item of listview is clicked, open another activity.
The problem is when I click on an item, nothing happens!
This code works fine in an Activity, but not in a Fragment.
Code:
ListView lv = (ListView) v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
});
I replaced this code :
ListView lv = (ListView) v.findViewById(android.R.id.list);
with :
ListView lv = getListView();
Because it was giving me
content view not yet created
in logcat.
All the code:
package rappage.rapfarsi.media.appteam;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class tab1 extends ListFragment {
static final String url_all_products = "http://aliak.xzn.ir/rap/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_PRODUCTS = "products";
final String TAG_PID = "pid";
final String TAG_NAME = "name";
// JSON Node names
// products JSONArray
JSONArray products = null;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1, container, false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = (ListView) v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity().getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
});
return v;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products 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_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I hope you can help me....thanks
Extending from ListFragment you only have to redefine this method:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Handle click event
}
Instead of getting the list and setting its onItemClickListener
i want to call an external picture and show it in a listview.
My code works for one second and crashes giving null pointer error. The code logic is like this
1.I have called First async task to fetch Json objects from outside.
Then created a custom adapter to set that objects in custom layout.
2.second async task gets one of the object(which contains the url for the image) and returns Bitmap image.
Could you identify what i did wrong ?
Eroor: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object referenc
My Fragment class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
String my_url;
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
View ImageView;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
int count = 1;
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put("ListCount",String.valueOf(i));
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
//get the bitmap url
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
}else{
thisview.setText("Normal line");
}
my_url = objects.get(position).get(GUID);
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
return convertView;
}
}//
}// end async task
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//
}
The custom layout:
?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="wrap_content"
android:background="#444444"
android:padding="10dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/img"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/headertext"
android:layout_gravity="center_horizontal"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="20dp"
android:fontFamily="http://fonts.googleapis.com/css?family=Roboto:700"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/headercontent"
android:layout_gravity="center_horizontal"
android:textColor="#ffffff"
android:maxLines="2"/>
</LinearLayout>
I can suppose the following problem: you have 2 different custom layout:
R.layout.list_item_header
R.layout.list_item
And, according to your code, you are calling for both of them:
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
If the ImageView R.id.img is NOT in both these layouts, your app will crash. If I'm right, you just need to fix your if/else and invoke the DownloadImageTask only when needed.
Eroor: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference clearly says that the ImageView parameter that you are passing in the constructor is NULL.
You are initializing this graphical unit at the runtime. Why not initialize it in the beginning like
Variable_name = (ImageView) convertView.findViewById(R.id.img)
in the OnCreateView..
and pass the created object where you are currently using it. This might solve your error.
Some Tweak in the condition - and works. It was conflict in which view i wanted to set.
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
I am making a listview, which shows data from a server. I get no errors in LogCat, but my ListView doesn't appear. This is my code:
package com.imptmd.charliemacdonald.desleutelaar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SlotenFragment extends ListFragment {
private ProgressDialog nDialog;
// URL to get contacts JSON
private static String url = "http://charlenemacdonald.com/sloten.json";
// JSON Node names
private static final String TAG_SLOTEN = "slotenlijst";
private static final String TAG_SLOT = "Slot";
// contacts JSONArray
JSONArray sloten= null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> slotenLijst;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSloten extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Even geduld a.u.b., studenten worden geladen...");
nDialog.setCancelable(false);
nDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
sloten = jsonObj.getJSONArray(TAG_SLOTEN);
// looping through All Contacts
for (int i = 0; i < sloten.length(); i++) {
JSONObject c = sloten.getJSONObject(i);
String Slot = c.getString(TAG_SLOT);
// tmp hashmap for single contact
HashMap<String, String> sloten = new HashMap<String, String>();
// adding each child node to HashMap key => value
sloten.put(TAG_SLOT, Slot);
// adding contact to contact list
slotenLijst.add(sloten);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
}
}
The INTERNET permission is already added in the Manifest, just as WRITE EXTERNAL STORAGE and INTERNAL STORAGE. I get no errors in LogCat. The only error I get is in the ADB 'ADB rejected connection to client'. Is that why my ListView doesn't appear? Thanks in advance.
Hi can you update you code and test the below logic what you received.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
Log.d("DataSize: ",""+slotenLijst.size());
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
Let us know what you get in log cat "DataSize".
Change your onCreateView(...) to be:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
// ListFragment implement this in default
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
//getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
and your fragment layout fragment_sloten could be like:
<?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:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
... ...
</LinearLayout>
Hope this help!
I am working on an android project. I want to add onClick event to listView so that whenever someone clicks on any item in the ListView new fragment showing further details is displayed.I am using Mysql database.
package com.example.festipedia_logo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.example.festipedia_logo.Searchpage.LoadAllProducts;
//import com.example.connection.disp;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class details1 extends SherlockFragment {
ArrayAdapter<String> adapter;
String[] city;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
EditText b;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.43.185:8080/festipedia/get_all_products.php";
Button a;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "eventname";
// products JSONArray
JSONArray products = null;
ListView l;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.second);
View rootView = inflater.inflate(R.layout.home2, container, false);
// setContentView(R.layout.all_products);
l = (ListView) rootView.findViewById(R.id.myListView);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
return rootView;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products 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_all_products, "GET", params);
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
//l.setFilterText(id);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] {
TAG_NAME},
new int[] { R.id.name });
// updating listview
l.setAdapter(adapter);
}
});
}
}
}
Try this..
Add below ItemClickListener Codes before return rootView;
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do something
}
});
You need to use OnItemClickListener and add/replace existing fragment in the container.
l.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Toast.makeText(getActivity(), "Clicked at" + position, Toast.LENGTH_SHORT).show();
}
});
Also you need not have runOnUiThread in onPostExecute as it is invoked on the ui thread.
You also need to use interface as a call back to the Activity and then add/replace fragment to the container in Activity
Exmple #
How to send data from fragment to fragment within same fragment activity?
Add ItemClickListener below
l = (ListView) rootView.findViewById(R.id.myListView);
in function onCreateView();
l.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do something
}
});