Android - Ayuda con un Proyecto

 
Vista:

Ayuda con un Proyecto

Publicado por Luis Rodriguez (8 intervenciones) el 18/11/2017 03:44:38
les presento lo siguiente:

a) Base de datos sql server 2016

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE A_Ciudades
(
[IdCiudad] [int] NOT NULL,
[NombreCiudad] [varchar](35) NOT NULL,
PRIMARY KEY CLUSTERED
(
[IdCiudad] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

b) Web Service (c# Aplicación de Servicios WCF)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Service1.svc.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
 
namespace WcfService1
{
public class Service1 : IService1
{
private string conStr = "Data Source =.; Initial Catalog=.; uid=sa; pwd=.";
 
public List<A_Ciudades> GetA_Ciudades()
{
List<A_Ciudades> A_CiudadesList = new List<A_Ciudades>();
	SqlConnection connection = new SqlConnection(this.conStr);
connection.Open();
SqlCommand cmd = new SqlCommand("select NombreCiudad from A_Ciudades order by IdCiudad desc", connection);
cmd.CommandType = CommandType.Text;
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
 {
A_Ciudades rha = new A_Ciudades ();
rha.NombreCiudad= sdr["NombreCiudad"].ToString();
A_CiudadesList.Add(rha);
}
return A_Ciudades List.ToList();
}
}
}

IService1.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
 
namespace WcfService1
{
[ServiceContract]
public interface IService1
{
 
[OperationContract]
[WebGet(UriTemplate = "GetA_Ciudades")]
List<A_Ciudades> GetA_Ciudades ();
}
 [DataContract]
public class A_Ciudades
{
string nombreciudad; [DataMember] public string NombreCiudad { get { return nombreciudad; } set { nombreciudad = value; } }
}
}

c) Android Studio
LAYOUT ciudades

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<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:orientation="vertical"
    tools:context="com.apppruebadef.Ciudades">
 
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay">
                <TextView
                    android:id="@+id/date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:textColor="@color/colorTexto"
                    android:textSize="20sp"
                />
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>
    <include layout="@layout/ cont_ciudades"/>
</android.support.design.widget.CoordinatorLayout>

LAYOUT cont_ciudades
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:text="center"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.apppruebadef.Ciudades"
        tools:showIn="@layout/ciudades">
 
            <GridView
                android:id="@+id/txtGrid"
                android:paddingLeft="6dp"
                android:paddingRight="6dp"
                android:paddingTop="6dp"
                android:paddingBottom="6dp"
                android:verticalSpacing="6dp"
                android:layout_width="wrap_content"
                android:layout_height="180dp"
                android:layout_gravity="center"
                android:animationCache="true"
                android:columnWidth="180dp"
                android:isScrollContainer="false"
                android:numColumns="2"
                android:stretchMode="spacingWidth"
                android:textFilterEnabled="false"
                tools:layout_editor_absoluteX="8dp"
                tools:layout_editor_absoluteY="8dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true”>
            </GridView>
</RelativeLayout>

LAYOUT ciudades_list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:paddingBottom="4dp"
    android:paddingLeft="4dp"
    android:paddingRight="4dp"
    android:paddingTop="4dp"
    android:weightSum="1">
 
    <TextView
        android:id="@+id/txtNombre"
        style="@android:style/Widget.Button.Inset"
        android:layout_width="178dp"
        android:layout_height="36dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="Nombre Ciudad"
        android:textAppearance="@style/TextAppearance.AppCompat"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14dp"
        android:textStyle="bold" />
 
    <TextView
        android:id="@+id/txtNombreCiudad"
        android:layout_width="89dp"
        android:layout_height="24dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/ txtNombre "
        android:gravity="bottom|center"
        android:text="  "
        android:textAppearance="@style/TextAppearance.AppCompat"
        android:textColor="@color/colorFondo"
        android:textSize="14dp"
        android:textStyle="bold" />
 
    <ImageView
        android:id="@+id/txtImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ txtNombre "
        android:layout_toEndOf="@+id/ txtNombreCiudad "
 
</RelativeLayout>

JAVA
Ciudades

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
 
public class Ciudades extends AppCompatActivity {
 
    ArrayList<HashMap<String, String>> CiudGrid;
    ListAdapter adapter;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ciudades);
 
 
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
 
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(500);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TextView tdate = (TextView) findViewById(R.id.date);
                                long date = System.currentTimeMillis();
                                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                                String dateString = sdf.format(date);
                                tdate.setText(dateString);
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };
        t.start();
 
 
        CiudGrid = new ArrayList<HashMap<String, String>>();
        GridView Grid = (GridView) findViewById(R.id.txtGrid);
        new GetA_CiudadesList(Ciudades.this,Grid).execute("http://0.0.0.00:0000/service1.svc/GetA_Ciudades");
 
    }
 
    class GetA_CiudadesList extends AsyncTask<String, Void, String> {
        String status= null;
        Activity context;
        GridView gridView;
 
 
        public GetA_CiudadesList(Activity context, GridView gridView){
            this.context =context;
            this.gridView=gridView;
        }
 
        protected void onPreExecute(){
 
 
        }
 
        protected String doInBackground(String... connUrl){
            HttpURLConnection conn=null;
            BufferedReader reader;
            try{
                final URL url=new URL(connUrl[0]);
                conn=(HttpURLConnection) url.openConnection();
                conn.addRequestProperty("Content-Type", "application/json; charset=utf-8");
                conn.setRequestMethod("GET");
                int result = conn.getResponseCode();
                if(result==200){
                    InputStream in=new BufferedInputStream(conn.getInputStream());
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder sb=new StringBuilder();
                    String line = null;
                    while((line=reader.readLine())!=null){
                        status=line;
                    }
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
            return status;
        }
 
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            if(result!=null){
 
                try{
                    ArrayList<String> stringArrayList = new ArrayList<String>();
                    JSONArray jsonArray = new JSONArray(result);
                    for(int i=0; i<jsonArray.length(); i++){
                        JSONObject object = jsonArray.getJSONObject(i);
                        String NombreCiudad= object.getString("NombreCiudad");
                        HashMap<String, String> itemList = new HashMap<String, String>();
                        itemList.put("NombreCiudad",NombreCiudad);
                        CiudGrid.add(itemList);
                    }
                    adapter = new SimpleAdapter(Ciudades.this, CiudGrid,R.layout.ciudades_list,
 
                            new String[]
                                      {
                                              "NombreCiudad"
                                      },
                              new int[]
                                      {
                                              R.id.txtNombreCiudad,
 
                                      });
 
                    ((AdapterView<ListAdapter>) gridView).setAdapter(adapter);
 
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }else{
                Toast.makeText(A5_0_Result_Anim_Trad.this,"Could not get any data.",Toast.LENGTH_LONG).show();
            }
 
        }
 
    }
}
hasta ahí funciona bien que deseo hacer pero no lo he conseguido todavía en la carpeta drawable están almacenadas un serie de imágenes de ciudades lo que se quiere es cuando la app lea de la base de datos el nombre le la ciudad que se mostrara en el TextView= txtNombreCiudad, muestre la imagen correspondiente en el ImageView= txtImg

es decir si en la base de datos en el NombreCiudad se registra londres, en el txtNombreCiudad se muestra londres (eso lo realiza) que debe hacer la app cuando se muestre londres en el TextView el ImageView se debe cargar con la Imagen correspondiente el cual llevara el nombre londres.png y de esa forma se ira llenado en GridView

Les agradezco si es posible hacerlo con lo que tengo de código o existe otra forma de hacerlo
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder