Passing data from listview to edittext of another activity - java

package com.supdeco.oussamaniba.loginapp;
import android.content.ClipData;
import android.content.Intent;
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.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", String.valueOf(listView.getSelectedItem()));
startActivity(intent);
}
});
}
}
I try to pass data from this ListView to another EditText in an other
activity but the result is always null, I want to pass all the text
string from the ListView to the EditText.

Do this way,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
intent.putExtra("username", YourModels.get(position).getUsername());//here first get position and than pass data you want to pass
intent.putExtra("fk_Code", "" + YourModels.get(position).getFk_Code());//take data from your model
startActivity(intent);
}
});
Check this link for more information.

It was too simple i found a simple solution i created a bunch of
string arrays that contains each of the data fetched from the DB and
stored in them, so now i can choose from those String arrays by
position, but thanks anyway
package com.supdeco.oussamaniba.loginapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DisplayListView extends AppCompatActivity {
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
TextView lstv;
String username,email,password,name,last;
List<String> susername = new ArrayList<String>();
List<String> sname = new ArrayList<String>();
List<String> slname = new ArrayList<String>();
List<String> spassword = new ArrayList<String>();
List<String> semail = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView) findViewById(R.id.list);
lstv = (TextView) findViewById(R.id.lstv);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
username = JO.getString("username");
email = JO.getString("email");
password = JO.getString("password");
name = JO.getString("name");
last = JO.getString("lastname");
Contacts contacts = new Contacts(username,email,password,name,last);
contactAdapter.add(contacts);
count++;
susername.add(username);
sname.add(name);
slname.add(last);
spassword.add(password);
semail.add(email);
lstv.setText("Available: " + count + " members");
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id)
{
Intent intent = new Intent(getApplicationContext(), SingleUser.class);
String[] N = new String[sname.size()];
N = sname.toArray(N);
String[] L = new String[slname.size()];
L = slname.toArray(L);
String[] U = new String[susername.size()];
U = susername.toArray(U);
String[] P = new String[spassword.size()];
P = spassword.toArray(P);
String[] E = new String[semail.size()];
E = semail.toArray(E);
intent.putExtra("name", N[position]);
intent.putExtra("last", L[position]);
intent.putExtra("username", U[position]);
intent.putExtra("password", P[position]);
intent.putExtra("email", E[position]);
startActivity(intent);
}
});
}
}

Related

ANDROID: Get next item from listview to editText after 1st item is saved

What I have: (1st Functionality)
I have a listview activity populated with items from JSON url. I have another activity where I get the listItem to editText field and then click "save", which saves the value to dB.
What I additionally want: (2nd Functionality)
When I click save, rather than going back to listview and select next listItem, I want the editText to fill the new listItem for me. But I am making errors in every step.
Below is the code that I have for 1st Functionality. I know it is just few lines to achieve the 2nd functionality but struggling with that.
The problem here is I cannot call the list String variable from one
activity to another and assign position or a counter to it. Suggest me
what to change here.
MainActivity.java (Class containing ListView populated with item from json url)
package com.example.app.listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
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.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> tutorialList = new ArrayList<String>();
private final static String URL = "-----json------url----file";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FetchDataTask().execute(URL);
}
private class FetchDataTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result= null;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(httpGet);
inputStream = response.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
Log.i("App", "Data received:" +result);
}
else
result = "Failed to fetch data";
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String dataFetched) {
//parse the JSON data and then display
parseJSON(dataFetched);
}
private String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private void parseJSON(String data){
try{
JSONArray jsonMainNode = new JSONArray(data);
int jsonArrLength = jsonMainNode.length();
for(int i=0; i < jsonArrLength; i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String postTitle = jsonChildNode.getString("codeid");
tutorialList.add(postTitle);
}
// Get ListView object from xml
listView = (ListView) findViewById(R.id.list);
// Define a new Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, tutorialList);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, AddFlowerInfo.class);
intent.putExtra("Code", listView.getItemAtPosition(i).toString());
startActivity(intent);
}
});
}catch(Exception e){
Log.i("App", "Error parsing data" +e.getMessage());
}
}
}
}
editText.java (class containing editText field and save to dB)
package com.example.app.listview;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;
import android.view.View;
public class AddFlowerInfo extends AppCompatActivity {
EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
private static final String TAG = "AddFlowerInfo";
Button savedata;
String noneditcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_flower_info);
editText = (EditText) findViewById(R.id.codeid);
savedata = (Button) findViewById(R.id.saveflowerinfo);
final String Codeholder = getIntent().getStringExtra("Code");
editText.setText(Codeholder);
}
public void dataflowerinfo(View view){
noneditcode = editText.getText().toString();
String method = "FlowerInfo";
BackgroundTask2 backgroundTask2 = new BackgroundTask2(this);
backgroundTask2.execute(method, noneditcode);
finish();
}
UPDATE AddFlowerInfo.java (OnCreate) and (OnClick)
public class AddFlowerInfo extends AppCompatActivity {
EditText editText; //non editable codeid <<----<<----<<----<<--<<---<<1
private static final String TAG = "AddFlowerInfo";
Button savedata;
int i=0;
String noneditcode;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_flower_info);
editText = (EditText) findViewById(R.id.codeid);
savedata = (Button) findViewById(R.id.saveflowerinfo);
Intent i =getIntent();
final ArrayList<String> list = i.getStringArrayListExtra("key");
pos = i.getIntExtra("position", 0);
// final String Codeholder = getIntent().getStringExtra("Code");
editText.setText(list.get(pos));
savedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddFlowerInfo.this, AddFlowerInfo.class);
startActivity(intent);
++pos;
if(pos<=list.size()-1)
list.get(pos);
}
});
Pass your data from activity like this
ArrayList<String> tutorialList = new ArrayList<String>();
Intent intent = new Intent(ActivityName.this, Second.class);
intent.putStringArrayListExtra("key", tutorialList);
startActivity(intent);
To retrive at AddFlowerInfo
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("key");
Then as you are retrieving data from list using position ,each time after saving call data at next position
You need to send complete array to AddFlowerInfo with the position, so change your onItemClick code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, AddFlowerInfo.class);
intent.putExtra("position", i);
intent.putStringArrayListExtra("array",tutorialList);
startActivity(intent);
}
});
Now in AddFlowerInfo:
Intent i = getIntent();
ArrayList<String> tutorialList = i.getStringArrayListExtra("array");
int pos=i.getIntExtra("position",0);
Use this position to get item from tutorialList.
To update data when user gets back to previous activity, place this code:
new FetchDataTask().execute(URL);
into onResume method.
Update
After saving first item to edit second item use:
++pos;
if(pos<=tutorialList.size()-1)
editText.setText(tutorialList.get(pos));
else
{
// you are after last item do whatever you want
}

getExtra Interface with Intent

I want to move Interface array called DisplayItem
this is activity1 code:
package com.example.eranp.clientpage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Main2Activity extends Activity implements Serializable{
private EditText pro_device_det;
private Button saveDataBase, btnViewAll ;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem, db;
private Spinner spinner;
private String option1, option2,option3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
db = FirebaseDatabase.getInstance().getReference();
databaseCustomer = FirebaseDatabase.getInstance().getReference("customer");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
option1 = getResources().getString(R.string.option1u);
option2 = getResources().getString(R.string.option2u);
option3 = getResources().getString(R.string.option3u);
saveDataBase = (Button) findViewById(R.id.save_btn);
btnViewAll = (Button)findViewById(R.id.button_viewAll);
final List<String> list = new ArrayList<String>();
list.add(option1);
list.add(option2);
list.add(option3);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
final Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
int urgency = spinnerUrgency(spinner);
Problem problem = new Problem(id, date, proDeviceDet, urgency, shortProDeviceDet);
databaseProblem.child(id).setValue(problem);
DisplayItem[] displayItem= new DisplayItem[]{customer, problem};
final int REQ_CODE = 1;
Intent intent2 = new Intent(Main2Activity.this, CustomersPage.class);
intent2.putExtra("DisplayItem",displayItem);
startActivity(intent2);
Toast.makeText(Main2Activity.this , "Customer added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Main2Activity.this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
The Interface code:
package com.example.eranp.clientpage;
import java.io.Serializable;
/**
* Created by Eran P on 15/04/2018.
*/
public interface DisplayItem extends Serializable {
}
this is the second activity that I want to move the interface code:
package com.example.eranp.clientpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class CustomersPage extends Activity {
ListView listViewCustomers;
List<Customer> customers;
List<Problem> problems;
List<Device> devices;
DatabaseReference databaseCustomers, databaseProblem, databaseDevice,db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customers_page);
db = FirebaseDatabase.getInstance().getReference();
databaseCustomers = FirebaseDatabase.getInstance().getReference("customer");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
listViewCustomers = (ListView)findViewById(R.id.listViewCostumers);
customers = new ArrayList<>();
devices = new ArrayList<>();
problems = new ArrayList<>();
Intent intentl = getIntent();
listViewCustomers.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Customer customer = customers.get(i);
showUpdateDeleteDialog(customer.getCustomerId(), customer.getfName() + " " + customer.getlName());
return true;
}
});
listViewCustomers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Customer customer = customers.get(i);
Problem problem = problems.get(i);
Device device = devices.get(i);
Intent intent = new Intent(CustomersPage.this, ClientPageData.class);
intent.putExtra("fName", customer.getfName());
intent.putExtra("lName", customer.getlName());
intent.putExtra("phone", customer.getPhoneNum());
intent.putExtra("email", customer.geteMail());
intent.putExtra("problemShort", problem.getProDeviceDet());
intent.putExtra("nameDevice", device.getDeviceName());
intent.putExtra("modelDevice", device.getDeviceModel());
startActivity(intent);
}
});
}
private void showUpdateDeleteDialog(final String customerId, String customerName) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextFName = (EditText) dialogView.findViewById(R.id.ET_fName);
final EditText editTextLName = (EditText) dialogView.findViewById(R.id.ET_lName);
final EditText editTextPhone = (EditText) dialogView.findViewById(R.id.ET_phone);
final EditText editTextEmail = (EditText) dialogView.findViewById(R.id.ET_email);
final EditText editTextProDetDev = (EditText) dialogView.findViewById(R.id.ET_proDetDevice);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(customerName);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String fName = editTextFName.getText().toString().trim();
String lName = editTextLName.getText().toString().trim();
String phone = editTextPhone.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String proDetDevice = editTextProDetDev.getText().toString().trim();
if (!TextUtils.isEmpty(fName)) {
updateCustomer(customerId, fName, lName,phone,email, proDetDevice);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteCustomer(customerId);
}
});
}
private boolean deleteCustomer(String id) {
//getting the specified Customer reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("customer").child(id);
DatabaseReference dRP = FirebaseDatabase.getInstance().getReference("device").child(id);
DatabaseReference dRD = FirebaseDatabase.getInstance().getReference("problem").child(id);
//removing Customer
dR.removeValue();
dRP.removeValue();
dRD.removeValue();
Toast.makeText(getApplicationContext(), "Customer Deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateCustomer(String id, String fName, String lName, String phone, String email, String proDetDevice) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("customer").child(id);
DatabaseReference dRp = FirebaseDatabase.getInstance().getReference("problem").child(id);
//updating artist
Customer customer= new Customer(id, fName, lName, email,phone);
dR.setValue(customer);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
String shortProDeviceDet = string3Words(proDetDevice);
Problem problem= new Problem(id, date,proDetDevice,0, shortProDeviceDet );
dRp.setValue(problem);
Toast.makeText(getApplicationContext(), "Customer Updated", Toast.LENGTH_LONG).show();
return true;
}
//attaching value event listener
databaseCustomers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
customers.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting customer
Customer customer = postSnapshot.getValue(Customer.class);
//adding customer to the list
customers.add(customer);
}
Intent intent2 = getIntent();
DisplayItem [] displayItem = (DisplayItem[]) intent2.getExtras().getSerializable("DisplayItem");
//creating adapter
CustomerAdapter customerAdapter = new CustomerAdapter(CustomersPage.this,displayItem );
//attaching adapter to the listview
listViewCustomers.setAdapter(customerAdapter);
}
}
when I tried to run the app this crashed and in the log file he says error in this line:
DisplayItem [] displayItem = (DisplayItem[])
intent2.getExtras().getSerializable("DisplayItem");
Thank you very much for helping!
Your code is not too clear but try use this format:
//When you want to pass an array as intent:
private ArrayList<String> arrayList = new ArrayList<String>();
Intent intent = new Intent();
intent.putStringArrayListExtra("data", arrayList);
startActivity(intent);
// To receive intent in the second activity
private ArrayList<String> newArrayList = new ArrayList<String>();
newArrayList = getIntent.getStringArrayListExtra("data");
Check if your classes Device and Customer implements serializable

Attaching a JSON array to list view

I am new to Java so please excuse any silly or obvious mistake. I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view. I am getting the dreaded red squiggly lines and what is to me a cryptic error message. Here is my code. I appreciate any assistance.
package --Hidden--;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class tracklist extends Activity implements OnItemClickListener {
private static final String URL = "http://rickthompson.com/json/fetchtracks.php";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracklist);
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.rowlayout, R.id.label, profileUserOptions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
///////////// login script
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("tracks")) {
Toast.makeText(getApplicationContext(), "tracks " + jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();
/// save user id in prefs
JSONArray contacts = jsonObject.getJSONArray("tracks");
HashMap<String, String> trackview = null;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String isrc = c.getString("isrc");
trackview = new HashMap<>();
trackview.put("isrc", isrc);
}
trackview.toString();
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
} else {
Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String userid = userPrefs.getString("memberid", "");
hashMap.put("u", userid);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
hashMap.put("sg", selectedSubGenre);
return hashMap;
}
};
requestQueue.add(request);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
}
}
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}
In the above code I hope you are trying to get "name" array which should be
JSONArray jso3 = new JSONArray (jsonObject.getString("names"));
Please provide the error details so that i can give you a detailed description.

i use Glide for my image display in android studio but how can i implement Glide to my listview?

I need help from anyone.. please respect my question..
ok, my problem is i want to use Glide for my listview but i dont know to do..
please constract my listviewadapter so that the Glide will work give me any other possible solution to achieve my goal..
my goal is i just want to display image and text in listview or gridview with Glide and JSON, the JSON result is from my php script..
here is my code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
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.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import com.bumptech.glide.Glide;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Just use : Glide.with(context)
.load(resultp.get(CategoryFragment.products_image))
.into(products_image);
in place of
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
in your ListViewAdapter.java

Creating a search app but listview is blank

I am building a search app using fragments for each screen. I have the search working and storing the JSON results in an ArrayList<Map<String, String>>in the main activity so the other fragments can access it. the current problem is on my resultsFragment I have a Google MapFragment embedded in the main ListFragment and a listView below that. The map is successfully populated, but the list is empty. I have spent hours trying to figure this out. Here is the code for resultsFragment
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.Map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ResultsFragment extends ListFragment {
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results, container, false);
//Get search results from stored ArrayList
resultsList = MainActivity.getResultsList();
//Build listView from results
ListView lv =(ListView) getActivity().findViewById(android.R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), resultsList,
R.layout.custom_row_view, new String[] { "AgencyID", "AgencyName",
"Address1" }, new int[] { R.id.text1, R.id.text2,
R.id.text3 });
// updating listview
setListAdapter(adapter);
//Setup embedded Google Map fragment
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Add markers to the map from resultsList
for (int i = 0; i < resultsList.size(); i++) {
Double latitude = Double.valueOf(resultsList.get(i).get("Lat"));
Double longitude = Double.valueOf(resultsList.get(i).get("Lng"));
String mname = resultsList.get(i).get("AgencyName");
LatLng posit = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(posit)
.title(mname));
}
return rootView;
}
}
In case its helpful here is the code from my homeFragment (where the search results are stored to the ArrayList)
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import com.wny.wecare.handler.JSONParser;
public class HomeFragment extends Fragment implements OnItemSelectedListener, OnClickListener{
private OnFragmentInteractionListener mListener;
private Spinner spinner;
private Button btnSubmit;
private static final String[] list={"Alden", "Amherst", "Angola",
"Blasdell", "Boston", "Bowmansville", "Buffalo", "Cheektowaga", "Clarence",
"Depew", "Derby", "East Aurora", "Eden", "Elma", "Getzville", "Gowanda",
"Grand Island", "Holland", "Irving", "Kenmore", "Lackawanna", "Lake View",
"Lancaster", "Lawtons", "North Collins", "Orchard Park", "Snyder", "Springville",
"Tonawanda", "West Seneca", "Williamsville"};
// Setup ArrayList from main activity to store results
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray agency = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnSubmit = (Button) rootView.findViewById(R.id.town_search);
btnSubmit.setOnClickListener(this);
spinner =(Spinner)rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return rootView;
}
// Check if parent activity implements the interface
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener =
(OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//add items into spinner dynamically
/*public void addItemsOnSpinner2(View v) {
addItemsOnSpinner2(v);
final List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}*/
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.town_search:
String town = (String) spinner.getSelectedItem().toString();
agencySearch(town);
mListener.onFragmentButton();
break;
case R.id.zip_search:
String strZip = ((EditText) v.findViewById(R.id.txt_zip)).getText().toString().trim();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;
/*case R.id.btn_location:
String strZip = v.findViewById(R.id.txt_zip).toString();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;*/
}
}
#Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
public void agencySearch(int zsearch) {
// Setting the URL for the Search by Zip
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_zip.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("zip", Integer.toString(zsearch)));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
}

Categories