list view setChecked() selects multiple items instead of one - android

I have a listview which populates the data using CheckedTextView. Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="14dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:textColor="#color/blue"
android:checked="false"
android:id="#+id/listviewsubview_textview" >
</CheckedTextView>
On item click listener, show tick on the right of the item, but not only that item shows tick other multiple items also show tick. Wierd thing is all are ticks after same number of row. I dont know where I am doing wrong.
Here is the code
package com.chegg.android.account;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.chegg.android.R;
import com.chegg.android.api.RestClient;
import com.chegg.android.objects.StudentInfo;
import com.chegg.android.util.Util;
public class MajorActivity extends MainActivity {
public ListView majorsListView;
public String url;
public HashMap<String, String> majorMap = new HashMap<String, String>();
public JSONArray resultArray = new JSONArray();
public JSONObject resultObj = new JSONObject();
public ArrayList<String> majorNameArray = new ArrayList<String>();
public RestClient restClient = null;
public StudentInfo studentInfo = null;
public HashMap majors = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.majors);
Object campusObj = this.getIntent().getStringExtra("campus_id");
restClient = new RestClient();
if(campusObj!=null) {
String campusId = campusObj.toString();
url = "school/majors/"+campusId;
} else {
url = "school/majors";
}
String result = restClient.connect(url);
try {
JSONArray jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
majorMap.put(name,jsonObj.getString("id"));
majorNameArray.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
majorsListView = (ListView)findViewById(R.id.majors_listview);
majorsListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
majorsListView.setAdapter(new ArrayAdapter<String>(MajorActivity.this, R.layout.list_view_subview,majorNameArray));
studentInfo = (StudentInfo)this.getIntent().getSerializableExtra("studentInfo");
if(studentInfo.getMajors()!=null) {
majors = (HashMap)studentInfo.getMajors();
} else {
majors = new HashMap();
}
//majorsListView.setAdapter(new MajorsAdapter(MajorActivity.this, R.layout.list_view_subview,majorNameArray,majors));
majorsListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CheckedTextView selectedView = (CheckedTextView)view;
Drawable chevron = getResources().getDrawable(R.drawable.chevron);
chevron.setBounds( 0, 0, chevron.getMinimumWidth(), chevron.getMinimumHeight() );
String text = selectedView.getText().toString();
if(!selectedView.isChecked()) {
selectedView.setChecked(true);
selectedView.setCheckMarkDrawable(R.drawable.chevron);
majors.put(text, majorMap.get(text));
} else {
selectedView.setChecked(false);
selectedView.setCheckMarkDrawable(null);
if(majors.containsKey(text)) {
majors.remove(text);
}
}
JSONObject jsonFinalResult = new JSONObject();
try {
Iterator it = majors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
JSONObject jsonObj = new JSONObject();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
jsonObj.put("name", pairs.getKey());
jsonObj.put("id",pairs.getValue());
resultArray.put(jsonObj);
}
jsonFinalResult.accumulate("majors", resultArray);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "account?access_token="+ accessToken;
Log.i("json *****",jsonFinalResult.toString());
String result = restClient.connectHttpsPostPutJson(url, jsonFinalResult.toString(), "PUT");
Log.i("*******",result);
String checkError = Util.checkResponseForError(result);
if(checkError.equals("") || checkError == null) {
studentInfo = StudentInfo.getObjectFromJson(result);
cacheData(studentInfo, "studentInfo", "update");
} else {
alertbox.setMessage(checkError);
alertbox.setNeutralButton("ok", null);
alertbox.show();
}
}
});
}
}
Any help is appreciated

majorsListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
That should be ListView.CHOICE_MODE_MULTIPLE, so Android will track your selections for you. Then, you can also get rid of your OnItemClickListener. When the user is done making selections, getCheckedItemPositions() will tell you which ones they chose, so you can update your data model.
Your current implementation ignores the effects of row recycling (one CheckedTextView widget will be used for any number of possible positions in your ArrayAdapter).

Related

Listview to get all data in list in JSON format

I using listview to display the response from API, which is a JSON object. Below listview, a button will be there. On clicking that button I need to get all the data from listview in JSON format.
Activity Class
package com.aryvart.myaromasupply;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import com.aryvart.myaromasupply.Adapter.CartListAdapterKV;
import com.aryvart.myaromasupply.Bean.CommonBean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartPageKV extends Activity implements MyInterface {
String json = null;
List<CommonBean> movieList = new ArrayList<>();
RecyclerView recyclerView;
CartListAdapterKV mAdapter;
Context context;
CoordinatorLayout coordinatorLayout;
Button btn_submit;
HashMap<String, JSONObject> hsFilterGmap;
String value;
JSONArray jsonArray;
ListView llView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page_kv);
context = this;
recyclerView = (RecyclerView) findViewById(R.id.my_recyclerView);
btn_submit = (Button) findViewById(R.id.btn_submit);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
llView = (ListView) findViewById(R.id.ll_view);
loadJSONFromAsset();
//Response API
try {
JSONObject obj = new JSONObject(json);
Log.e("NN", "json-->" + obj.toString());
JSONArray respArray = obj.getJSONArray("results");
Log.e("NN", "respArray-->" + respArray.toString());
for (int i = 0; i < respArray.length(); i++) {
JSONObject jsonObj = respArray.getJSONObject(i);
CommonBean drawerBean = new CommonBean();
drawerBean.setStr_cart_id(jsonObj.getString("id"));
drawerBean.setStr_cart_title(jsonObj.getString("name"));
drawerBean.setStr_quan(jsonObj.getString("quantity"));
drawerBean.setStr_tot_quant(jsonObj.getString("total_quantity"));
movieList.add(drawerBean);
}
// Getting adapter by passing xml data ArrayList
mAdapter = new CartListAdapterKV(movieList, context, (MyInterface) context);
llView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
//Button Click Event
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("NN:fc", String.valueOf(hsFilterGmap));
Iterator myVeryOwnIterator = hsFilterGmap.keySet().iterator();
JSONArray jsonArray = new JSONArray();
while (myVeryOwnIterator.hasNext()) {
String key = (String) myVeryOwnIterator.next();
JSONObject value1 = hsFilterGmap.get(key);
Log.e("NN:value", value1.toString());
jsonArray.put(value1);
}
Log.e("NN:fcAr", jsonArray.toString().replaceAll("\\\\", ""));
System.out.println("the JSON ARRAY is" + jsonArray.toString());
}
});
}
public String loadJSONFromAsset() {
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
// Interface to get Checked value from listview(Hashmap for not allowing duplicates)
#Override
public HashMap<String, JSONObject> getUnCheckedVal(HashMap<String, JSONObject> strVal, String str_removed_id) {
hsFilterGmap = strVal;
Log.e("NN:fc", String.valueOf(hsFilterGmap));
return hsFilterGmap;
}
}
Adapter Class
package com.aryvart.myaromasupply.Adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.aryvart.myaromasupply.Bean.CommonBean;
import com.aryvart.myaromasupply.MyInterface;
import com.aryvart.myaromasupply.R;
import com.like.LikeButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartListAdapterKV extends BaseAdapter {
private List<CommonBean> commonBeanList;
Context c;
MyInterface my_interface;
private static LayoutInflater inflater = null;
HashMap<String, JSONObject> hsMap = new HashMap<String, JSONObject>();
// constructor
public CartListAdapterKV(List<CommonBean> movieList, Context context, MyInterface inter) {
this.commonBeanList = movieList;
Log.e("NN", "size-->" + this.commonBeanList);
this.c = context;
this.my_interface = inter;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return commonBeanList.size();
}
public Object getItem(int position) {
return commonBeanList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.cart_items_kv, parent, false);
TextView txt_cartTitle;
final CheckBox cb_box;
txt_cartTitle = (TextView) view.findViewById(R.id.textView2);
cb_box = (CheckBox) view.findViewById(R.id.checkBoxKV);
final CommonBean recyclerBean = commonBeanList.get(position);
cb_box.setChecked(true);
txt_cartTitle.setText(recyclerBean.getStr_cart_title());
//check if checkbox is checked. if yes the add value to hashmap(by default all checkboxes will be checked in listview
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
//JSONArray req = new JSONArray();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
//adding the json object in hashmap to remove duplicates
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
cb_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
final CommonBean recyclerBean = commonBeanList.get(position);
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
On initial clicking of a button, I'm getting the data which is in the foreground (visible to the user), once I scroll remaining data's are getting.
Can anyone help how can I get entire values in listview in on button click?
Open this cart_items_kv xml and place the button.
Go to the adapter
and make the event there.You can get the data of an item by position in adapter.
another solution
add a click after finding view
public ViewHolder(View itemLayoutView) {
// here `enter code here`
itemLayoutView.setOnClickListener(this);
}

Android ListView - Loop json_encode in PHP but only show one row in ListView

I want to take data json form PHP file that have been loop and put it into array list(ListView) in my android activity but its only show one row in Listview that is the first row from json.
Here my table that in my activity :
my table
Here my PHP file :
<?php
$con = mysqli_connect("xxxx","xxxx","xxxx","xxxx");
$nama_klp = $_POST["nama_klp"];
$sql2 = "select id_klp from kelompok where nama_klp ='$nama_klp' ";
$result2 = mysqli_query($con, $sql2);
$followingdata2 = $result2->fetch_assoc();
$id_klp = $followingdata2['id_klp'];
$sql2 = "select id_mhs from praktikan where id_klp ='$id_klp' ";
$result2 = mysqli_query($con, $sql2) or die("Error in Selecting " . mysqli_error($con));
while($row2 =mysqli_fetch_assoc($result2))
{
$id_mhs = $row2['id_mhs'] ;
$sql = "select nama_mhs from mahasiswa where id_mhs ='$id_mhs' ";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
$response = array();
while($row =mysqli_fetch_assoc($result))
{
$response[] = $row ;
}
echo json_encode($response);
}
?>
It returns a json string in this format:
[{"nama_mhs":"iyan2"}][{"nama_mhs":"illiyan"}][{"nama_mhs":"12"}][{"nama_mhs":"12"}]
Here my activity code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DaftarNilaiUtama2 extends AppCompatActivity {
ListView LvMhs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daftar_nilai_utama2);
TextView tvMatkul = (TextView) findViewById(R.id.tvNamaMatkul);
TextView tvKlp = (TextView) findViewById(R.id.tvNamaKlp);
Intent intent = getIntent();
String matkul = intent.getStringExtra("matkul");
String klp = intent.getStringExtra("klp");
tvMatkul.setText(matkul);
tvKlp.setText(klp);
LvMhs = (ListView) findViewById(R.id.lvMhs);
final TextView text = (TextView) findViewById(R.id.textView4);
String nama_klp = (String) tvKlp.getText();
Response.Listener responseListener= new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
List<String> item = new ArrayList<String>();
JSONArray jsonMainNode = new JSONArray(response);
JSONObject jsonResponse = new JSONObject();
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonResponse = jsonMainNode.getJSONObject(i);
String nama_mhs = jsonResponse.optString("nama_mhs");
item.add(nama_mhs);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DaftarNilaiUtama2.this, android.R.layout.simple_list_item_1, android.R.id.text1, item);
LvMhs.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RequestLvIdMhs lvReq = new RequestLvIdMhs(nama_klp, responseListener);
RequestQueue queue = Volley.newRequestQueue(DaftarNilaiUtama2.this);
queue.add(lvReq);
}
}
My server request code:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by callbee on 27/05/2016.
*/
public class RequestLvIdMhs extends StringRequest {
private static final String LvMhs_URL = "http://192.168.1.10/KartuKontrolApp/LvIdMhs-DNilaiU2.php";
private Map<String, String> params;
public RequestLvIdMhs(String nama_klp, Response.Listener<String> listener) {
super(Method.POST, LvMhs_URL, listener, null);
params = new HashMap<>();
params.put("nama_klp", nama_klp);
}
public Map<String, String> getParams() {
return params;
}
}
your php json string is wrong it should be like following string.
{"data1":[{"nama_mhs":"iyan2"}],"data2":[{"nama_mhs":"illiyan"}],"data3[{"nama_mhs":"12"}],"data4":[{"nama_mhs":"12"}]}
now you can pars all arrays using the respective key, for that you have to change your java code too.

Need help regarding integrating android functions with premade views

I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?
If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?

Android: Passing HashMap between Activity and Fragments

I am a newbie to Android development, and I have encountered a halt in my application development. I hope somebody can help me out here.
I have an activity named JSONActivity and inside JSONActivity, I extract JSON data from a web url, and store it into 3 HashMaps, depending on the type of data.
I would like to pass a HashMap to 3 different Fragments. I'll start with just doing it for one fragment however, I cannot seem to pass the data.
Can somebody point out what I am doing wrong, and what I can do to fix it?
I can assure that the json extraction works fine, because the data can be rendered using a Toast
JSONActivity.java
package com.example.json;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import android.app.Activity;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.os.AsyncTask;
public class JSONActivity extends Activity {
HashMap<Integer,String> imageList = new HashMap<Integer,String>();
HashMap<Integer,String> textList = new HashMap<Integer,String>();
HashMap<Integer,String> otherList = new HashMap<Integer,String>();
private static final String ID = "id";
private static final String TYPE = "type";
private static final String DATA = "data";
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of json items: " +
jsonArray.length());
//---print out the content of the json feed---
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt(ID);
String type = jsonObject.getString(TYPE);
String data = jsonObject.getString(DATA);
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);
// Toast.makeText(getBaseContext(), jsonObject.getString("type") +
// " - " + jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ReadJSONFeedTask().execute(
"sample url (not shown in this post)");
}
}
Fragment1.java:
package com.example.json;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class fragment1 extends ListFragment {
#SuppressWarnings("unchecked")
public HashMap<Integer,String> textList =
(HashMap<Integer, String>) getArguments().getSerializable("textList");
public String[] vals = new String[textList.size()];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)textList.values().toArray()[i];
return inflater.inflate(R.layout.fragment1, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(getActivity(),
"You have selected " + vals[position], Toast.LENGTH_SHORT).show();
}
}
fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_weight="0.5" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.json.Fragment1"
android:layout_width="0dp"
android:layout_height="300dp"
android:layout_weight="0.5" />
</LinearLayout>
You need to define a setter method in your fragments which will set the HashMap property of fragment and display it to the user. After that when you done parsing json data call it like this:
((Fragment1) getSupportFragmentManager.findFragmentById(R.id.fragment1)).setAndDisplayJSONDataMethod(valuesToShow);
and setAndDisplayJSONDataMethod method will be something like this:
public void setAndDisplayJSONDataMethod(HashMap<Integer, String> valuesToShow) {
String[] vals = new String[textList.size()];
for(int i = 0; i < textList.size(); i++)
vals[i] = (String)valuesToShow.values().toArray()[i];
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, vals));
}
For now it doesn't work cause you're trying to get/set your list data in a wrong place and in a wrong time. Read about Fragments and Fragments/Actvities lifecycles.
In java, strings have to be compared with equals or equalsIgnoreCase
if(type.equals("text"))
textList.put(id,data);
else if(type.equals("other"))
otherList.put(id,data);
else if(type.equals("image"))
imageList.put(id,data);

How to get a specific String out from a ListView Item

What I'm trying to do
Hello Guys, I'm creating an App for a friend of mine, i simply show his Channel in my App. I get the Data of the Videos over JSON.
Now I found a Problem. When I filled the data into my ListView over the SimpleListAdapter and try to get it over an OnItemClickListner and retrieve them over lv.getItemAtPosition(position); I get all data which is stored in the specific row. But I only need the Link/Url I saved in that field.
Question
Like you read I got more than one information in my ListView to be exactly there are four Strings (Thumb,Title, Content, Link). But I only need to get the String of the Link, how can I do this, down here you find the Code.
Code
test2.java
package de.stepforward;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class test2 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
String line = null;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//get the Data from URL
try{
URL url = new URL("http://gdata.youtube.com/feeds/mobile/users/TheStepForward/uploads?alt=json&format=1");
URLConnection conn = url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//read d response till d end
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.v("log_tag", "Append String " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try{
JSONObject json = new JSONObject(result);
JSONObject feed = json.getJSONObject("feed");
JSONArray entrylist = feed.getJSONArray("entry");
for(int i=0;i<entrylist.length();i++){
//Get Title
JSONObject movie = entrylist.getJSONObject(i);
JSONObject title = movie.getJSONObject("title");
String txtTitle = title.getString("$t");
Log.d("Title", txtTitle);
//Get Description
JSONObject content = movie.getJSONObject("content");
String txtContent = content.getString("$t");
Log.d("Content", txtContent);
//Get Link
JSONArray linklist = movie.getJSONArray("link");
JSONObject link = linklist.getJSONObject(0);
String txtLink = link.getString("href");
Log.d("Link", txtLink);
//Get Thumbnail
JSONObject medialist = movie.getJSONObject("media$group");
JSONArray thumblist = medialist.getJSONArray("media$thumbnail");
JSONObject thumb = thumblist.getJSONObject(2);
String txtThumb = thumb.getString("url");
Log.d("Thumb", txtThumb.toString());
//String Array daraus machen und in Hashmap füllen
HashMap<String, String> map = new HashMap<String, String>();
map.put("Thumb", txtThumb);
map.put("Title", txtTitle);
map.put("Content", txtContent);
map.put("Link", txtLink);
mylist.add(map);
}
//ListView füllen
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.lit,
new String[] { "Thumb","Title","Content","Link"},
new int[] { R.id.img_video,R.id.txt_title,R.id.txt_subtitle});
setListAdapter(adapter);
//OnClickLister um Youtube-Video zu öffnen
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
lv.getItemAtPosition(position);
}
});
}catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
Thank you in Advance
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Map<String, String> map = mylist.get(position);
String link = map.get("Link");
}
});
Better way is to wrap your information in an Object and download the data from internet and make an Object and add it to any ArrayList.
For Example:
You will make an Java Object class. say: VideoInfo
public class VideoInfo
{
String title, content, link, thumb;
// define there setter getter
// also a constructor with these params
public VideoInfo(String title,String content,String link,String thumb)
{
//set Values accordingly
}
}
make a class level ArrayList
ArrayList<VideoInfo> myList = new ArrayList<VideoInfo>();
and when you get data from server parse it and save it like this way:
myList.add(new VideoInfo(txtTitle, txtContent, txtLink, txtThumb));
You will need customization of Adapter (e.g override getView()) to set data from your custom Ojbect (VideoInfo).
and then in your ListActivity in OnItemClickListener you will get your desired object like this way:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// you have class level ArrayList myList.
myList.get(position).getLink(); //getLink() will be the getter of you field link in VideoInfo
}
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
HashMap<String, String> selectedHashMapObject = (HashMap<String, String>)lv.getItemAtPosition(position);
String selectedLink = selectedHashMapObject.get("Link");
}
For example, you can do something similar like this:
for(int i = 0; i < ((ListView)lv).getItemCount(); i++){
Map<String, String> currentView = (Map<String, String>) ((ListView)lv).getItemAtPosition(i);
String cVId = currentView.get("id");
}
i think you can use this
http://developer.android.com/reference/android/widget/CursorAdapter.html#getItem(int).
Cursor cursor = (Cursor) simple.getItem(position);
// retrieve the data from the cursor

Categories

Resources