How to display selected installed applications in grid view - java

**I have this code to show the installed applications in Android. I also want to display the selected applications by the user in Grid view. How can I do that in this code?
And is there always a need for adapter for grid-view also?**
This is my first activity:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Startup extends Activity {
Button bIns, bSel;
ArrayList<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bIns = (Button) findViewById(R.id.bList);
bSel = (Button) findViewById(R.id.bGrid);
}
public void viewList(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
public void viewGrid(View view) {
myList = (ArrayList<String>) getIntent().getSerializableExtra("mySelectedList");
Intent intent = new Intent(getApplicationContext(), Last.class);
intent.putExtra("mySelectedList",myList);
startActivity(intent);
}
}
This is my second activity:
package com.abhi.test;
import java.util.ArrayList;
import com.abhi.test.ApplicationAdapter;
import java.util.List;
import com.example.applist.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
Button button;
Bundle bundle;
CheckBox checkbox;
ArrayList<ApplicationInfo> selectedapplication = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
button = (Button) findViewById(R.id.button);
checkbox = (CheckBox) findViewById(R.id.cb_app);
new LoadApplications().execute();
//Intent intent = new Intent(this,Last.class);
}
public void selectedApps(View view) {
//new ApplicationAdapter().selApps();
selectedapplication = ApplicationAdapter.finalList;
Intent intent = new Intent(MainActivity.this, Startup.class);
intent.putExtra("mySelectedList",selectedapplication);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (packageManager.getLaunchIntentForPackage(info.packageName) != null)
{
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.row, applist);
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
}
}
Array adapter for second activity:
package com.abhi.test;
import java.util.ArrayList;
import java.util.List;
import com.example.applist.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
int position1;
CheckBox checkBox;
private PackageManager packageManager;
public ArrayList<Boolean> checkList = new ArrayList<Boolean>();
private OnCheckedChangeListener listener;
public static ArrayList<ApplicationInfo> finalList = null;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
for (int i = 0; i < appsList.size(); i++)
{
checkList.add(false);
}
}
#Override
public int getCount() {
if (appsList != null) {
return appsList.size();
} else {
return 0;
}
}
#Override
public ApplicationInfo getItem(int position) {
if (appsList != null) {
return appsList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override //ibuilt function getView()--responsinle for making views
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Understand
view = layoutInflater.inflate(R.layout.row, null);
}
ApplicationInfo data = appsList.get(position);
if (data != null) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
position1=position;
checkBox = (CheckBox) view.findViewById(R.id.cb_app); //understand
checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
checkBox.setChecked(checkList.get(position)); // set the status as we stored it
checkBox.setOnCheckedChangeListener(mListener); // set the listener
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
/* if(checkBox.isChecked())
{
finalList.add(data);
Toast.makeText(getContext(), "App Added", Toast.LENGTH_LONG).show();
}*/
}
return view;
}
OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
}
};
}
This is the last activity in which I want to show the selected applications by the user:
package com.abhi.test;
import java.util.ArrayList;
import com.example.applist.R;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class Last extends Activity{
GridView gridview;
ArrayList<ApplicationInfo> appList;
String[] appName = new String[100];
String[] appPack = new String[100];
String[] appComp = new String[100];
ArrayList<String> appInfo = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.last);
gridview = (GridView) findViewById(R.id.gridview);
appList = (ArrayList<ApplicationInfo>) getIntent().getSerializableExtra("mylist");
for(int i=0;i<appList.size();i++)
{
appName[i] = appList.get(i).name;
appPack[i] = appList.get(i).packageName;
appComp[i] = appName[i]+appPack[i];
appInfo.add(appComp[i]);
}
/* ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
android.R.layout.simple_list_item_1, appInfo);
gridview.setAdapter(adapter);*/
}
}
XML for the first activity:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<Button
android:id="#+id/bList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewList"
android:text="#string/bInstalledApps" />
<Button
android:id="#+id/bGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="fill_horizontal"
android:onClick="viewGrid"
android:text="#string/bSelectedApps" />
</LinearLayout>
XML for the second activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="selectedApps"
android:text="Done"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/button" />
</RelativeLayout>
row.xml for adapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/appdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cb_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:scaleX="1.50"
android:scaleY="1.50" />
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp" >
<TextView
android:id="#+id/app_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_paackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
XML for the last activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</LinearLayout>

A GridView is a collection of views in a grid. The Android system doesn't magically know what views you want to be in it. This is where the adapter comes in. By setting an adapter for a GridView, you tell the GridView several things about how you want it to display views including how many views there are and what each view looks like. So yes, all GridViews need adapters.

Related

how to display recyclerview in a fragment after fetching an api on the click of a button

I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment. I am using recycler view inside the search fragment to display the data below the search bar and the button.
Here is the code for the fragment_search.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SearchFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="-230dp"
android:src="#drawable/home_oval" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FOODIES"
android:textSize="40dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:queryHint="Find your today's recipe"
android:iconifiedByDefault="false"
android:background="#drawable/searchoval"
android:id="#+id/searchbar"
/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="search"
android:background="#drawable/rounded_btn"
android:layout_below="#+id/searchbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button1"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_man_searching_location_using_gps_2127154_0"
android:layout_below="#+id/button1"
android:id="#+id/searching_logo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searching_text"
android:text="Search for yummy delicacies today"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:fontFamily="#font/quicksand"
android:layout_below="#+id/searching_logo"
android:textSize="25dp"
android:textColor="#color/black"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:id="#+id/recycler_view"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</FrameLayout>
Here is my SearchFragment.java file.
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "http://localhost:5000/" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonArrayRequest);
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I am fething the api and setting the arraylists and adapter inside the onClick listener
but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.
Here is the code for the adapter.
package com.example.recipeappandroid.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
private Context mContext;
private ArrayList<Recipe> mRecipe;
public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
mContext = context;
mRecipe = recipe;
}
public void setData(ArrayList<Recipe> mRecipe) {
this.mRecipe = mRecipe;
}
#NonNull
#Override
public recipeViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
return new recipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull recipeViewHolder viewHolder, int i) {
Recipe recipe = mRecipe.get(i);
Picasso.get().load(recipe.getImg()).into(viewHolder.image);
viewHolder.recipe_title.setText(recipe.getTitle());
viewHolder.recipe_data.setText(recipe.getData());
}
#Override
public int getItemCount() {
return mRecipe.size();
}
}
Here is my solution
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);
//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();

fragment and appcompact activity error

I tried to create a bar tabs in two activities (Testactivity and Page1 related with adapters for recylerview and listview...), but those activities classes are extended already to AppCompatActivity because I use some codes needs AppCompatActivity.
I try to write something like (public class Testactivity extends AppCompatActivity, Fragment) but it still shows the errors:
'onStop()' in 'android.support.v7.app.appcompatactivity' clashes with 'onStop()' in 'android.support.v4.app.fragment'; attempting to assign weaker access privileges 'protected'; was 'public' class cannot extend multiple classes
this is my MainActivity class:
import android.support.design.widget.TabLayout;
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.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
Testactivity tab1 = new Testactivity();
return tab1;
case 1 :
Page1 tab2 = new Page1();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "ACCUEIL";
case 1:
return "MON COMPTE";
}
return null;
}
}
}
Testactivity class:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Testactivity extends AppCompatActivity, Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_testactivity,
container, false);
return rootView;
}
ArrayList<articles> arrayList;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testactivity);
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.ListView1);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
}
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(content);
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("articles");
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articlesobject = null;
try {
articlesobject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
arrayList.add(new articles(
articlesobject.getString("picture"),
articlesobject.getString("title")
));
} catch (JSONException e1) {
e1.printStackTrace();
}
CustomListAdaper adaper = new CustomListAdaper(
getApplicationContext(), R.layout.custom_list_layout,
arrayList
);
lv.setAdapter(adaper);
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
}
Page1 class:
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class Page1 extends AppCompatActivity, Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_page1, container,
false);
return rootView;
}
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
EditText txt_email, txt_mdp;
Button btn_enter;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
openHelper=new DatabaseHelper(this);
db = openHelper.getReadableDatabase();
txt_email=(EditText)findViewById(R.id.txt_email);
txt_mdp=(EditText)findViewById(R.id.txt_mdp);
btn_enter=(Button)findViewById(R.id.btn_enter);
btn_enter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String mdp = txt_mdp.getText().toString();
String e = txt_email.getText().toString();
cursor = db.rawQuery("SELECT *FROM " + DatabaseHelper.TABLE_NAME
+ " WHERE " + DatabaseHelper.COL_5 + "=? AND " + DatabaseHelper.COL_4 +
"=?", new String[]{e, mdp});
if (cursor != null)
{
if (cursor.getCount() > 0) {
cursor.moveToNext();
Toast.makeText(getApplicationContext(), "Bienvenue",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(Page1.this,
Testactivity.class));
}
else
{
Toast.makeText(getApplicationContext(), "Erreur",
Toast.LENGTH_SHORT).show();
}
}
}
});}
public void btn_i (View v)
{
Intent intent = new Intent(Page1.this, Page2.class);
startActivity(intent);
}
}
activity_testactivity xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="com.example.lenovo.myapplication.MainActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/logo2" />
<ListView
android:id="#+id/ListView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
</LinearLayout>
</RelativeLayout>
activity_page1 xml:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lenovo.myapplication.MainActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/logo2" />
<EditText
android:id="#+id/txt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email (adresse éléctronique)"
android:inputType="textPersonName"
android:visibility="visible" />
<EditText
android:id="#+id/txt_mdp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Mot de passe"
android:inputType="textPersonName"
android:visibility="visible" />
<Button
android:id="#+id/btn_enter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_green_dark"
android:text="Connexion"
android:textColor="#android:color/background_light"
android:visibility="visible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="258dp">
<Button
android:id="#+id/btn_mdpo"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_weight="0.18"
android:text="Mot de passe oublié" />
<Button
android:id="#+id/btn_i"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_weight="0.18"
android:onClick="btn_i"
android:text="Créer un compte" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
when i run the project, 2 errors coming:
C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Page1.java
error:'{'expected
and
C:\Users\lenovo\Desktop\Nouveau dossier\MyApplication\app\src\main\java\com\example\lenovo\myapplication\Testactivity.java
error:'{'expected
the { must be before fragment in
public class Page1 extends AppCompatActivity, Fragment
and
public class Testactivity extends AppCompatActivity, Fragment
Any help will be appreciated!
As the following error says:
'onStop()' in 'android.support.v7.app.appcompatactivity' clashes with 'onStop()' in 'android.support.v4.app.fragment'; attempting to assign weaker access privileges 'protected'; was 'public' class cannot extend multiple classes
it is because Java language doesn't support multiple inheritance more about it at Why not multiple inheritance?
So, the following code is wrong:
public class Page1 extends AppCompatActivity, Fragment {
...
}
You need to extend the Page1 either with AppCompatActivity or Fragment but not both.
Because you want to use FragmentPagerAdapter with the following:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
...
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
...
}
}
which is need Fragment as the return of getItem(). So, you need to extend the Page1 and Testactivity with Fragment.

Why isn't async stopping from recreating listview?

Wasn't really sure how to ask this but...
My code is meant to generate ListView input on a button click.
When I click the button it should .execute() an Async which takes a list of items and adds them to an ArrayList< HashMap < String, String > > with a custom adapter.
The problem is, when I press the button, it generates the list and adds it to the ListView, however, instead of going... 1, 2, 3, 4, 5, ....20 it goes in a random order. 1, 2, 5, 1, 3, 0, 6, 7, 8, 3, 1 ...
And if I scroll up or down the ListView it changes.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/bLoadData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Load api data" />
<ListView
android:id="#+id/lvMovies"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/bLoadData"
android:background="#efefef" />
</RelativeLayout>
results_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:id="#+id/ivPosters"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/place_holder_img"/>
<TextView
android:id="#+id/results_layout_tv_movie_name"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingStart="20dp"
android:paddingTop="10dp"
android:text="hellow"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
MainActivity.class:
package com.example.zdroa.testinggrounds;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
static ArrayList<HashMap<String, String>> posters;
ListView listView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvMovies);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println(posters.get(position).values().toString());
}
});
button = (Button) findViewById(R.id.bLoadData);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posters = new ArrayList<>();
ImageLoadTask ilt = new ImageLoadTask();
ilt.execute();
}
});
}
private class ImageLoadTask extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
posters = getPathFromAPI();
return posters;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
SearchAdapter adapter = new SearchAdapter(MainActivity.this, result);
listView.setAdapter(adapter);
}
private ArrayList<HashMap<String, String>> getPathFromAPI() {
String moviePaths[] = new String[10];
for (int i = 0; i < moviePaths.length; i++) {
HashMap<String, String> map = new HashMap<>();
String s = "path";
map.put(s, s + "_" + i);
moviePaths[i] = "path_" + i;
posters.add(map);
}
return posters;
}
}
}
SearchAdapter.class:
package com.example.zdroa.testinggrounds;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
public class SearchAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String, String>> array;
private ImageView imageView;
private TextView textView;
SearchAdapter(Context context, ArrayList<HashMap<String, String>> paths) {
mContext = context;
array = paths;
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.results_layout, null);
imageView = (ImageView) convertView.findViewById(R.id.ivPosters);
textView = (TextView) convertView.findViewById(R.id.results_layout_tv_movie_name);
}
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.place_holder_img);
String link_end = array.get(position).values().toString();
Picasso.with(mContext)
.load("http://image.tmdb.org/t/p/w185" + link_end)
// .resize(width, (int) (width * 1.5))
.placeholder(drawable)
.into(imageView);
textView.setText(position+"");
return convertView;
}
}
Your imageview and textview references are only set when the convertview is null...move those lines out of the parenthesis.
in onPost in Asyntask class
after creating and setting the adapter for listview
make the list that you're using in list view
list=new ArrayList<>();

How to get value of a row in listview in android

I am new in android
The structure of my application consist of:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.reyhane.myapplication.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
cell.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layoutDirection="rtl">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/nationalCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:text="حذف" />
</TableRow>
</TableLayout>
MainActivity.java
package com.example.reyhane.myapplication;
import android.app.Activity;
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.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
public ListView list;
public ArrayList<Person> countries = new ArrayList<Person>();
public ListAdapter adapter;
public void fillPerson(String nationalCode) {
Person person = new Person();
person.setNationalCode(nationalCode);
person.setName("reza");
person.setLastName("hghgh");
person.setPhone("231345");
countries.add(person);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
fillPerson("6768767");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Object o = list.getItemAtPosition(position);
Person person = (Person) o;
openAddPersonActivity(person.getNationalCode());
}
});
}
public void openAddPersonActivity(String nationalCode) {
Intent i = new Intent(MainActivity.this, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
}
ListAdapter.java
package com.example.reyhane.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* Created by reyhane on 11/24/16.
*/
public class ListAdapter extends BaseAdapter {
MainActivity mainActivity;
ListAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public int getCount() {
return mainActivity.countries.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolderItem {
TextView nationalCode;
TextView name;
TextView lastName;
TextView phone;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.nationalCode = (TextView) convertView.findViewById(R.id.nationalCode);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolderItem) convertView.getTag();
}
Button deleteBtn = (Button) convertView.findViewById(R.id.delete_btn);
holder.nationalCode.setText(this.mainActivity.countries.get(position).getNationalCode());
holder.name.setText(this.mainActivity.countries.get(position).getName());
holder.lastName.setText(this.mainActivity.countries.get(position).getLastName());
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
mainActivity.countries.remove(position); //or some other task
notifyDataSetChanged();
}
});
return convertView;
}
}
My problem:
As you see in my application, i have list of person in listview.
In this form i add person and delete and edit it.
I can remove each record of listview but i can not get nationalCode value of person of each reacord in listview to fetch person from database by this nationalcode and edit it.
How do i do?
please help me
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
{
String nationalcode = (String) ((TextView) v.findViewById(R.id.nationalcode)).getText();
Toast.makeText(getApplicationContext(), "NATIONAL CODE "+nationalcode, Toast.LENGTH_SHORT).show();
openAddPersonActivity(nationalcode);
}
});
Hope it helps.
try this :
openAddPersonActivity(countries.get(position).getNationalCode());
FYI, the list.setOnItemClick doesn't work
add this into your ListAdapter:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mainActivity,"Country Code = "+MainActivity.countries.get(position).getNationalCode(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(mainActivity, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
});
and if you click country code in listview item then it will detected;
You have not set countries list to your Listview adaptor.
When you are setting the adaptor, pass the countries list to listview adaptor.
It work successfully:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nationalcode = (String) ((TextView) view.findViewById(R.id.nationalCode)).getText();
Toast.makeText(mainActivity, "NATIONAL CODE " + nationalcode, Toast.LENGTH_SHORT).show();
}
});
Try This
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Person person = countries.get(position);
openAddPersonActivity(person.getNationalCode());
}

How to start an activity on button press in ListView

I've done some research but I've found myself getting quite confused on the topic of ListViews and creating a button within a ListView.
For my project, I have a ListView created in one layout.xml (called recap_page.xml) and in another layout.xml (row_layout.xml) I have the layout view (the layout on row_layout.xml is what is displayed on recap page)
The rows are populated with data entered by the user in another activity using SQLiteDatabase (DataEntryHome.java) (not relevant for this, but I'm just giving some context)
Basically, what I want to do is to have the button in each row open a new activity. As it stands, when I press the button, the app crashes. I believe I have to use a method that links to the button by using onClick. I have tried this by creating a method called viewOrder although I'm not sure which activity I have to put the method in because I've confused myself by creating different activities for different purposes.
Is anyone able to help me and explain:
a) What steps I have to take to make these buttons responsive?
b) What activities do I need to implement them into?
My code
recap_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_view"
android:textColor="#000000"
android:clickable="true">
</ListView>
</RelativeLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#30609d">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/firstNameText"
android:text="First name here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/surnameText"
android:text="Surname here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/emailText"
android:text="Email here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/phoneText"
android:text="Phone here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/addInfoText"
android:text="Additional info"
android:gravity="center"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="53dp"
android:layout_height="37dp"
android:text="GO"
android:id="#+id/goButton"
android:onClick="viewOrder"
android:layout_marginTop="7dp"/>
</LinearLayout>
</ScrollView>
RecapPage.java
package com.example.joe.printedclothing;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecapPage extends AppCompatActivity{
String classNames[] = {"HomeActivity", "SelectDesign"};
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
}
ListDataAdapter.java
package com.example.joe.printedclothing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler {
TextView FIRSTNAME, SURNAME, EMAIL, PHONE, ADDINFO;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
return row;
}
}
And I don't know why, but here's my home activity:
package com.example.joe.printedclothing;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
public class HomeActivity extends AppCompatActivity {
private static Button StagHenButton, ReviewOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
StagHenButton = (Button) findViewById(R.id.StagHen); // Locates the button that the user presses to move to the next activity
StagHenButton.setOnClickListener( // When the button is clicked...create an intent to move to next activity
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent("com.example.joe.printedclothing.SelectDesign"); // Intent to choose next activity
startActivity(newIntent);
}
}
);
}
public void addContact (View view) {
Intent intent = new Intent(this,DataEntryHome.class);
startActivity(intent);
}
public void viewContact (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
public void viewOrder (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can set the OnClickListener in the Adapter.getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
layoutHandler.goButton = (Button) row.findViewById(R.id.goButton);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
layoutHandler.goButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//Start your activity here
}
}
);
return row;
}
Just put the below code in your function from where you want to launch new Activity.This is the tested code.It might be helpful for you
Intent i=new Intent(getContext(),Main2Activity.class);
getContext().startActivity(i);

Categories